package com.yuanfeng.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.yuanfeng.commoms.aspect.UserPermissionsResult;
import com.yuanfeng.commoms.aspect.UserService;
import com.yuanfeng.commoms.config.*;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.base.MemberMessageListIntegralDTO;
import com.yuanfeng.commoms.dto.base.UpMemberClassDTO;
import com.yuanfeng.commoms.dto.order.RefundParamDTO;
import com.yuanfeng.commoms.dto.order.WapGoodsSaleSumDTO;
import com.yuanfeng.commoms.dto.payment.AccountPeriodParamDTO;
import com.yuanfeng.commoms.dto.payment.GroupBookingParamDTO;
import com.yuanfeng.commoms.dto.payment.GroupBookingTradeDTO;
import com.yuanfeng.commoms.dto.payment.RefundAccountParamDTO;
import com.yuanfeng.commoms.dto.userms.ShopYgUserInfoDTO;
import com.yuanfeng.commoms.dto.userms.UserInfoDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.rocketmq.MqSendUtils;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.excel.ExcelsUtil;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.base.PlatformoperationVO;
import com.yuanfeng.commoms.vo.goods.GoodsDetailsListVO;
import com.yuanfeng.commoms.vo.goods.WapGoodsSaleSumUpdateVO;
import com.yuanfeng.commoms.vo.order.OrderBaseVO;
import com.yuanfeng.commoms.vo.order.OrderCommissionVO;
import com.yuanfeng.commoms.vo.payment.AccountShopBillDetailsVO;
import com.yuanfeng.commoms.vo.shop.AccountPeriodVO;
import com.yuanfeng.commoms.vo.shop.ManageShopAddressQueryVO;
import com.yuanfeng.commoms.vo.shop.RetentionShopInfoVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.order.dto.*;
import com.yuanfeng.order.entity.*;
import com.yuanfeng.order.feign.*;
import com.yuanfeng.order.mapper.*;
import com.yuanfeng.order.service.OrderReturnService;
import com.yuanfeng.order.service.OrderSupplierBaseService;
import com.yuanfeng.order.utils.DateUtil;
import com.yuanfeng.order.vo.*;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransactionContext;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class OrderReturnServiceImpl extends ServiceImpl<OrderReturnMapper, OrderReturnEntity>
        implements OrderReturnService {

    @Resource
    private OrderBaseMapper orderBaseMapper;
    @Resource
    private OrderGoodsMapper orderGoodsMapper;
    @Resource
    private OrderReturnPlatformMapper orderReturnPlatformMapper;

    @Resource
    private OrderCommissionMapper orderCommissionMapper;

    @Autowired
    private OrderSupplierBaseService orderSupplierBaseService;
    @Autowired
    private UserServiceClient userServiceClient;
    @Autowired
    private PayMentServiceClient payMentServiceClient;
    @Autowired
    private BusinessServiceClient businessServiceClient;
    @Autowired
    private BaseServiceClient baseServiceClient;
    @Autowired
    private ThirdPartyServiceClient thirdPartyServiceClient;
    @Autowired
    private GoodServiceClient goodServiceClient;
    @Resource
    private OrderSettlementMapper orderSettlementMapper;
    @Autowired
    private OrderComplaintsMapper orderComplaintsMapper;
    @Autowired
    private OrderBaseServiceImpl orderBaseService;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult applyRefund(Map<String, String> map) throws TransactionException {
        try {
            String token = map.get("token");
            if ("".equals(map.get("returnReasonId")) || "".equals(map.get("returnReason"))
                    || map.get("returnReasonId") == null || map.get("returnReason") == null) {

                return ResponseResult.fail(BizCodeEnume.PLEASE_COMPLETE_THE_REFUND_INFORMATION);
            }

            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);

            ResponseResult result = applyRefund(map, userInfo);
            return result;

        } catch (Exception e) {
            // 回滚
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            return ResponseResult.fail(e.getMessage());
        }

    }

    @Override
    public ResponseResult applyReturn(Map<String, String> map) throws TransactionException {

        String token = map.get("token");
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        ResponseResult result = applyReturn(map, userInfo);
        return result;
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult applyReturnMore(ApplyReturnOrderDTO applyReturnOrders) throws TransactionException {
        try {
            String token = applyReturnOrders.getToken();
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
            if (userInfo == null) {
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
            }
            if (applyReturnOrders.getReturnReasonId() == null || "".equals(applyReturnOrders.getReturnReasonId())) {
                return ResponseResult.fail(BizCodeEnume.RETURN_REASON_CANNOT_BE_NULL);
            }
            Map<String, String> sult = new HashMap<>();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            OrderBaseVO orderBase = orderBaseMapper.getOrderBaseById(applyReturnOrders.getOrderId());

            // 如果订单售后时间小于当前时间订单不可退
            if (orderBase.getVirtualGoods() != 0 && null != orderBase.getOrderLastReturnTime()
                    && DateUtils.compareDate(orderBase.getOrderLastReturnTime(), DateUtils.getNowDate())) {
                return ResponseResult.fail(BizCodeEnume.GOODS_BEYOND_THE_AFTER_SALES_PERIOD);
            }
            String orderId = applyReturnOrders.getOrderId();

            Integer shopId = orderBase.getShopId();
             //清空平台介入信息
             orderReturnPlatformMapper.delete(new LambdaQueryWrapper<OrderReturnPlatformEntity>()
                     .eq(OrderReturnPlatformEntity::getOrderId, String.valueOf(applyReturnOrders.getOrderId())));

             // 去userms模块查找用户信息 "sellerId","sellerName","shopId","userId"
             Map<String, String> getSerllerInfoMap = new HashMap<>();
             getSerllerInfoMap.put("shopId", orderBase.getShopId().toString());
             Map<String, String> sellerInfo = (Map<String, String>) userServiceClient.getSellerInfo(getSerllerInfoMap).getData();
             Integer orderGoodsNum = 0;
             // 根据商品己算退货价格
             List<ApplyReturnGoodDTO> applyReturnGoods = applyReturnOrders.getApplyReturnGoods();

             //判断当前订单是否全部退货
             Boolean huoBaoreturn = true;
             Double returnCash = 0.00;
             // 退货时商品总价格
             Double goodsAmount = 0.00;
             //售后红包金额
             Double returnRptCash = 0.00;
             //退还运费
             Double returnShippingFee = 0.00;
             //运费
             Double shippingFee = 0.00;
             //供应商 退还的 经销等级折扣
             BigDecimal orderDiscountFee = new BigDecimal(0);
             //查询运费
             List<OrderGoodsEntity> goodsNumList = orderGoodsMapper.selectList(new LambdaQueryWrapper<OrderGoodsEntity>()
                     .eq(OrderGoodsEntity::getOrderId, orderId));

             for (OrderGoodsEntity entity : goodsNumList) {
                 shippingFee += entity.getShippingFee().doubleValue();
             }
             for (ApplyReturnGoodDTO applyReturnGood : applyReturnGoods) {
                 // 查询商品购买数量
                 String orderGoodsId = applyReturnGood.getOrderGoodsId();

                 OrderGoodsEntity orderPurchaseQuantity = orderGoodsMapper.selectOne(new LambdaQueryWrapper<OrderGoodsEntity>()
                         .eq(OrderGoodsEntity::getOrderId, orderId)
                         .eq(OrderGoodsEntity::getGoodsId, orderGoodsId));
                 //商品价格
                 Double goodsPrice = orderPurchaseQuantity.getGoodsPrice();

                 goodsAmount += Double.parseDouble(applyReturnGood.getOrderGoodsNum()) * Double.parseDouble(applyReturnGood.getOrderGoodsPrice());
                 //商品价格加上售后促销价格
                 goodsAmount += orderPurchaseQuantity.getOrderRptPrice() + orderPurchaseQuantity.getVoucherPrice();
                 returnRptCash += orderPurchaseQuantity.getOrderRptPrice();
                 returnShippingFee += orderPurchaseQuantity.getShippingFee();

                 Integer orderGoodsNumTemp = new Double(orderPurchaseQuantity.getOrderGoodsNum()).intValue();
                 Integer orderReturnGoodsNum = Integer.valueOf(applyReturnGood.getOrderGoodsNum());
                 if (!orderGoodsNumTemp.equals(orderReturnGoodsNum)) {
                     huoBaoreturn = false;
                 }
                 // 判断：如果全部退则退还此商品实付，否则按比例退还
                 if (applyReturnGood.getOrderGoodsNum().equals(orderPurchaseQuantity.getOrderGoodsNum())) {
                     // 1.1 退回资金 = 应付金额（商品实际支付金额 + 运费- 促销）'
                     returnCash += orderPurchaseQuantity.getOrderGoodsPaymentAmount().doubleValue() - orderPurchaseQuantity.getShippingFee();
                     //全部退 退经销等级折扣
                     orderDiscountFee = orderBase.getDirectsellerDiscount();
                 } else {
                     if (null != orderBase.getOrderType() && 2 == orderBase.getOrderType()) {
                         // 退货金额 = ((实付金额-运费)/商品总金额)*退货商品价格*退货商品数量
                         returnCash += (orderBase.getOrderGoodsAmount().doubleValue() / Double.parseDouble(orderPurchaseQuantity.getOrderGoodsNum())) * Double.parseDouble(applyReturnGood.getOrderGoodsNum());

                     } else {
                         // 退货金额 = ((实付金额-运费)/商品总金额)*退货商品价格*退货商品数量
                         returnCash += ((orderPurchaseQuantity.getOrderGoodsPaymentAmount().doubleValue() - orderPurchaseQuantity.getShippingFee()) / Double.parseDouble(orderPurchaseQuantity.getOrderGoodsNum())) * Double.parseDouble(applyReturnGood.getOrderGoodsNum());

                     }
                     if (null != orderPurchaseQuantity.getOrderGoodsNum() && !"0".equals(orderPurchaseQuantity.getOrderGoodsNum())) {
                         orderDiscountFee = (orderBase.getDirectsellerDiscount().divide(new BigDecimal(orderPurchaseQuantity.getOrderGoodsNum()), 2, RoundingMode.HALF_UP)).multiply(new BigDecimal(applyReturnGood.getOrderGoodsNum()));
                     }
                 }
                 //如果是 供应商代发货的订单 查询供应商的商品价格 计算退单金额
                 //因为 同步是商品不能加购物车 所以 退货数量 和 退货商品价格是唯一
                 if (null != orderBase.getDropShipping() && 1 == orderBase.getDropShipping()) {
                     BigDecimal supperReturnPrice = new BigDecimal(0);
                     supperReturnPrice = orderBase.getGoodsPaymentAmount();
                     //将退单的供应商 退款金额存入数据库
                     orderSupplierBaseService.update(null, new LambdaUpdateWrapper<OrderSupplierBaseEntity>()
                             .eq(OrderSupplierBaseEntity::getOrderId, applyReturnOrders.getOrderId())
                             .set(OrderSupplierBaseEntity::getOrderReturnPrice, supperReturnPrice));
                 }
             }
             //如果huoBaoreturn 为true 证明当前订单 退货的商品数量与订单数量一致 （但也可能是一个订单里面的一个商品全部数量退货，另外的商品不退货，所以要判断是否是所有商品全部退货）
             if (!huoBaoreturn) {
                 //判断订单是否是全部商品 全部退货
                 Integer num = goodsNumList.size();
                 //如果是订单全部退货 就退红包（修改红包状态未使用，在商家退货确认收货接口修改），退红包 就在结算时写入红包金额
                 if (num.equals(applyReturnGoods.size())) {
                     //如果进来就证明该订单不是是全部退货就不退红包，不将红包金额写入结算  不退还 经销等级折扣
                     returnRptCash = 0.00;
                     returnShippingFee = 0.00;
                 }
             }
             //退货金额   取前端传的值
             returnCash = applyReturnOrders.getReturnCash();
             BigDecimal tmp = new BigDecimal(returnCash);
             returnCash = tmp.setScale(2, RoundingMode.HALF_UP).doubleValue();

             Integer one = orderBaseMapper.update(null, new LambdaUpdateWrapper<OrderBaseEntity>()
                     .eq(OrderBaseEntity::getOrderId, applyReturnOrders.getOrderId())
                     .set(OrderBaseEntity::getOrderStatus, CommonType.orderStatus.CONFIRM_RECEIPT.getCode())
                     .set(OrderBaseEntity::getOrderReturnStatus, CommonType.orderReturnStatus.RETURNING_GOODS.getCode())
                     .set(OrderBaseEntity::getReturnMethodType, CommonType.returnMethodType.RETURN.getCode())
                     // 1.1 退回资金
                     .set(OrderBaseEntity::getOrderRefundAmount, returnCash)
                     // 插入买家id，为资金回退做准备
                     .set(OrderBaseEntity::getSellerUserId, sellerInfo.get("userId")));

             //由于要展示退货详情所以商品表撤销是没清状态(所以二次申请要清空状态)
             Map<String, Object> orderGoodsMap1 = new HashMap<String, Object>();
             orderGoodsMap1.put("goodsRefundStatus", 0);
             orderGoodsMap1.put("goodsReturnStatus", 0);
             orderGoodsMap1.put("orderId", orderId);
             this.baseMapper.updateOrderGoodsById(orderGoodsMap1);

             Integer two = 0;
             for (ApplyReturnGoodDTO applyReturnGood : applyReturnGoods) {
                 orderGoodsNum += Integer.parseInt(applyReturnGood.getOrderGoodsNum());
                 two += orderGoodsMapper.update(null, new LambdaUpdateWrapper<OrderGoodsEntity>()
                         .eq(OrderGoodsEntity::getOrderId, applyReturnOrders.getOrderId())
                         .eq(OrderGoodsEntity::getGoodsId, applyReturnGood.getOrderGoodsId())
                         .set(OrderGoodsEntity::getOrderGoodsReturnnum, applyReturnGood.getOrderGoodsNum())
                         // 订单状态 与order同步
                         .set(OrderGoodsEntity::getOrderGoodsStatus, CommonType.orderStatus.CONFIRM_RECEIPT.getCode())
                         .set(OrderGoodsEntity::getGoodsReturnStatus, CommonType.orderReturnStatus.RETURNING_GOODS.getCode())
                         .set(OrderGoodsEntity::getGoodsRefundStatus, CommonType.orderRefundStatus.REFUNDING.getCode()));
             }

             Map<String, Object> orderReturnMap = new HashMap<>();
             Integer isExistData = this.baseMapper.selectCount(new LambdaQueryWrapper<OrderReturnEntity>()
                     .eq(OrderReturnEntity::getOrderId, applyReturnOrders.getOrderId()));

             this.baseMapper.updateOdbOrderReturn(applyReturnOrders.getOrderId());

             if (applyReturnOrders.getReturnVoucher() != null) {
                 List<String> voucher = applyReturnOrders.getReturnVoucher();
                 String returnVoucher = JSON.toJSONString(voucher);
                 orderReturnMap.put("returnVoucher", returnVoucher);
             }
             orderReturnMap.put("orderId", applyReturnOrders.getOrderId());
             orderReturnMap.put("returnState", 1);
             orderReturnMap.put("returnShopHandle", 1);
             // 1为退款申请,2为退货申请
             orderReturnMap.put("returnType", 2);
             orderReturnMap.put("returnCash", returnCash);
             orderReturnMap.put("returnMethodStatus", 3);
             orderReturnMap.put("returnReasonId", applyReturnOrders.getReturnReasonId());
             orderReturnMap.put("returnReason", applyReturnOrders.getReturnReason());
             orderReturnMap.put("returnMessage", applyReturnOrders.getReturnMessage());
             orderReturnMap.put("orderGoodsNum", orderGoodsNum);
             orderReturnMap.put("orderDiscountFee", orderDiscountFee);
             // 订单总额，包含运费
             orderReturnMap.put("orderAmount", orderBase.getOrderGoodsAmount().doubleValue() + orderBase.getOrderShippingFee());
             orderReturnMap.put("orderGoodsId", 0);
             orderReturnMap.put("orderGoodsName", 0);
             orderReturnMap.put("orderGoodsPrice", 0);
             orderReturnMap.put("orderGoodsPic", 0);
             orderReturnMap.put("buyerUserId", userInfo.getUserId());
             orderReturnMap.put("shopId", orderBase.getShopId());
             orderReturnMap.put("shopName", orderBase.getShopName());
             orderReturnMap.put("buyerUserAccount", userInfo.getUserName());
             orderReturnMap.put("returnAddrId", 0);
             orderReturnMap.put("returnPostCode", 0);
             // 待写退回红包金额
             DecimalFormat decimalFormat = new DecimalFormat("#.00");
             orderReturnMap.put("returnRptCash",
                     decimalFormat.format(returnRptCash));
             orderReturnMap.put("returnShippingFee",
                     decimalFormat.format(returnShippingFee));
             orderReturnMap.put("returnShopHandle", 1);
             // 插入买家id，为资金回退做准备
             orderReturnMap.put("sellerUserId", sellerInfo.get("userId"));
             orderReturnMap.put("returnMobile", orderBase.getOrderReceiverContact());

             if (isExistData == 1) {
                 OrderReturnStatusDTO returnStatus = this.baseMapper.queryOrderReturnData(applyReturnOrders.getOrderId());
                 // 存在更新数据
                 //在卖家没介入之前可以一直修改但不改失效时间
                 orderReturnMap.put("historicalReturnStatus", "");
                 if (returnStatus.getReturnState() != 1) {
                     SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                     Calendar calendar = Calendar.getInstance();
                     String nowDate = DateUtils.getTime();
                     Date date = null;
                     try {
                         date = formatter1.parse(nowDate);
                     } catch (ParseException e) {
                         e.printStackTrace();
                     }
                     calendar.setTime(date);
                     calendar.add(Calendar.DATE, 1);
                     //处理时效时间
                     Date calendarTime = calendar.getTime();
                     orderReturnMap.put("returnAddTime", nowDate);
                     orderReturnMap.put("expirationTime", formatter1.format(calendarTime));
                     if (returnStatus.getReturnState() == 3) {
                         Integer returnChangeNum = returnStatus.getReturnChangeNum() + 1;
                         orderReturnMap.put("returnChangeNum", returnChangeNum);
                     } else if (returnStatus.getReturnState() == 10) {
                         Integer resubmissionsNumber = Integer.valueOf(returnStatus.getResubmissionsNumber() + 1);
                         orderReturnMap.put("resubmissionsNumber", resubmissionsNumber);
                     }

                 }
                 // 更新申请退款记录
                 boolean isUpdateReturnSuccess = this.baseMapper.updateOrderReturn(orderReturnMap);

             } else {
                 // 退多件暂时不存
                 SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
                 String dateString = formatter.format(new Date());
                 String returnCode = "TD-" + userInfo.getUserId() + "-" + orderBase.getShopId() + "-" + dateString + "-"
                         + "0001";
                 // 退货编号
                 orderReturnMap.put("returnCode", returnCode);

                 SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                 Calendar calendar = Calendar.getInstance();
                 String nowDate = DateUtils.getTime();
                 Date date = null;
                 try {
                     date = formatter1.parse(nowDate);
                 } catch (ParseException e) {
                     e.printStackTrace();
                 }
                 calendar.setTime(date);
                 calendar.add(Calendar.DATE, 1);
                 //处理时效时间
                 Date calendarTime = calendar.getTime();
                 orderReturnMap.put("returnAddTime", nowDate);
                 orderReturnMap.put("expirationTime", formatter1.format(calendarTime));


                 double orderAmount = orderBase.getOrderGoodsAmount().doubleValue() + orderBase.getOrderShippingFee();

                 Integer three = this.baseMapper.returnMoney(orderReturnMap);

//             int three = insertOrderReturn(applyReturnOrders.getOrderId(), orderAmount, "0", "0", "0", orderGoodsNum.toString(), "0",
//                     "2", userInfo, orderBase, sellerInfo,
//                     applyReturnOrders.getReturnReasonId(), applyReturnOrders.getReturnReason(), applyReturnOrders.getReturnMessage(),
//                     returnCash, returnRptCash, decimalFormat.format(returnShippingFee));

                 if (1 != one || 0 == two || 1 != three) {
                     TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                     return ResponseResult.fail(BizCodeEnume.APPLICATION_FAILED);
                 }

                 // 使用feign在其他库插入数据
                 Map<String, String> userRecordMap = new HashMap<String, String>();
                 userRecordMap.put("orderId", applyReturnOrders.getOrderId());
                 userRecordMap.put("userId", userInfo.getUserId());
                 userRecordMap.put("userNickname", userInfo.getUserName());
                 // 1。1将总金额改为 退款金额
                 userRecordMap.put("recordMoney", returnCash.toString());
                 userRecordMap.put("recordDate", DateUtils.getTime());
                 userRecordMap.put("recordYear", DateUtils.getYear());
                 userRecordMap.put("recordMonth", DateUtils.getMonth());
                 userRecordMap.put("recordDay", DateUtils.getDay());
                 userRecordMap.put("recordTitle", "退款");
                 userRecordMap.put("recordDesc", "订单号：" + applyReturnOrders.getOrderId());
                 userRecordMap.put("recordTime", DateUtils.getTime());
                 userRecordMap.put("tradeTypeId", "5");
                 userRecordMap.put("userType", "1");
                 userRecordMap.put("recordStatus", "8");
                 userRecordMap.put("recordPayorder", orderBase.getPaymentNumber());
                 userRecordMap.put("recordPaytime", DateUtils.getTime());

                 Map<String, String> sellerRecordMap = new HashMap<String, String>();
                 sellerRecordMap.put("orderId", applyReturnOrders.getOrderId());
                 sellerRecordMap.put("userId", sellerInfo.get("userId"));
                 sellerRecordMap.put("userNickname", sellerInfo.get("sellerName"));
                 // 1。1将总金额改为 退款金额
                 sellerRecordMap.put("recordMoney", returnCash.toString());
                 sellerRecordMap.put("recordDate", DateUtils.getTime());
                 sellerRecordMap.put("recordYear", DateUtils.getYear());
                 sellerRecordMap.put("recordMonth", DateUtils.getMonth());
                 sellerRecordMap.put("recordDay", DateUtils.getDay());
                 sellerRecordMap.put("recordTitle", "退款");
                 sellerRecordMap.put("recordDesc", "订单号：" + applyReturnOrders.getOrderId());
                 sellerRecordMap.put("recordTime", DateUtils.getTime());
                 sellerRecordMap.put("tradeTypeId", "5");
                 sellerRecordMap.put("userType", "2");
                 sellerRecordMap.put("recordStatus", "8");
                 sellerRecordMap.put("recordPayorder", orderBase.getPaymentNumber());
                 sellerRecordMap.put("recordPaytime", DateUtils.getTime());

                 Map<String, Map<String, String>> returnMap = new HashMap<String, Map<String, String>>();
                 returnMap.put("user", userRecordMap);
                 returnMap.put("seller", sellerRecordMap);
                 // 使用feign在其他库插入数据
                 ResponseResult torf = payMentServiceClient.insertRecord(returnMap);
                 //发送消息通知给商家
                 String content = "您的会员" + userInfo.getUserName() + "提交了退货退款申请，请尽快处理";
                 orderComplaintsMapper.insertSysMessage1("", orderBase.getSellerUserId(),"",8,
                         "用户提交退货退款",content, String.valueOf(orderBase.getShopId()));

                 if (CommonStatusEnum.SUCCESS.getCode() != torf.getCode()) {
                     GlobalTransactionContext.reload(RootContext.getXID()).rollback();
                     return ResponseResult.fail(BizCodeEnume.APPLICATION_FAILED);
                 }
             }

        } catch (Exception e) {
            // 回滚
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            return ResponseResult.fail(e.getMessage());
        }
        return ResponseResult.success(BizCodeEnume.APPLICATION_SUCCESS.getMsg());
    }

    @Override
    public ResponseResult onlyReturnMoney(Map<String, Object> map) throws TransactionException {
        String token = map.get("token").toString();
        String userInfoString = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
        UserInfoDTO UserInfoDTO = JSON.parseObject(userInfoString, UserInfoDTO.class);
        UserInfoVO userInfo = UserInfoDTO.getUser();
        ResponseResult result = onlyReturnMoney(map, userInfo);
        return result;
    }

    @Override
    public ResponseResult listReturnOrderByRT(Map<String, Object> paraMap) {
        String token = (String) paraMap.get("token");
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (userInfo == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        paraMap.put("userId", userInfo.getUserId());


        List<String> userIdList = new ArrayList<>();
        userIdList.add(userInfo.getUserId());
        //新增企业成员信息
        paraMap.put("userIdList", userIdList);
        List<GoodsDetailsVO> goodsDetails;
        IPage<ReturnOrderVO> page = this.baseMapper.getBlogByType(new Query<ReturnOrderVO>().getPage(paraMap),
                paraMap);

        for (ReturnOrderVO returnOrder : page.getRecords()) {
            OrderReturnPlatformEntity pl = orderReturnPlatformMapper.selectOne(new LambdaQueryWrapper<OrderReturnPlatformEntity>()
                    .eq(OrderReturnPlatformEntity::getOrderId, returnOrder.getOrderId()));
            if(pl != null){
                returnOrder.setReturnState("9");
                returnOrder.setInterventionState(pl.getInterventionState());
            }
            if ("1".equals(returnOrder.getReturnType())) {
                goodsDetails = orderGoodsMapper.listGoodsDetails(returnOrder.getOrderId());

                returnOrder.setGoodsDetails(goodsDetails);
            } else {
                // 退货，只有一种商品情况
                Map<String, String> selectMap = new HashMap<>();

                selectMap.put("orderId", returnOrder.getOrderId());
                goodsDetails = orderGoodsMapper.listReturnGoods(selectMap);
                returnOrder.setGoodsDetails(goodsDetails);
            }
        }
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult returnDetail(Map<String, String> map) {
        String token = map.get("token");
        @SuppressWarnings("unused")
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        SellerOrderDetailVO sellerOrderDetail = this.baseMapper.getSellerOrderDetailById(map.get("returnCode"));
        if (sellerOrderDetail.getReturnVoucher() != null) {
            List<String> voucher = JSON.parseArray(sellerOrderDetail.getReturnVoucher(), String.class);
            sellerOrderDetail.setReturnVouchers(voucher);
        }
        Map<String, Object> expressMap = new HashMap<>(1);
        expressMap.put("token", token);
        //查找平台所有的快递公司
        ResponseResult expressQueryResults = baseServiceClient.queryExpressList(expressMap);
        if (null != expressQueryResults.getData()) {
            List<LinkedHashMap<Object, Object>> list = (List<LinkedHashMap<Object, Object>>) expressQueryResults.getData();
            for (LinkedHashMap<Object, Object> result : list) {
                if (null != result.get("expressId") && null != sellerOrderDetail.getReturnPostCode()) {
                    if (result.get("expressId").toString().equals(sellerOrderDetail.getReturnPostCode())) {
                        sellerOrderDetail.setReturnPostName((String) result.get("expressName"));
                    }
                }
            }

        }
        //如果是供应商的单
        if (null != sellerOrderDetail.getOrderType() && 2 == sellerOrderDetail.getOrderType()) {
            SellerOrderDetailVO sellerOrderDetail2 = this.baseMapper.queryDistributionDiscount(map.get("returnCode"));
            Double zhekou = (sellerOrderDetail2.getOrderDiscountFee() / Double.parseDouble(sellerOrderDetail2.getOrderGoodsNum())) * Double.parseDouble(sellerOrderDetail2.getOrderGoodsReturnNum());
            sellerOrderDetail.setReturnCash(sellerOrderDetail.getReturnCash());
        }

        Map<String, String> selectMap = new HashMap<String, String>();
        selectMap.put("orderId", sellerOrderDetail.getOrderId());
        Integer methodStatus = sellerOrderDetail.getOrderType();
        List<GoodsDetailsVO> listReturnGoods = null;
        if (null != methodStatus) {
            if (methodStatus == 2) {
                listReturnGoods = orderGoodsMapper.listReturnGoods(selectMap);
            } else {
                listReturnGoods = orderGoodsMapper.listReturnGoods1(selectMap);
            }
        }
        sellerOrderDetail.setGoodsDetails(listReturnGoods);

        //判断是否是代发货订单
        if (null != sellerOrderDetail.getDropShipping() && 1 == sellerOrderDetail.getDropShipping() && userInfo.getShopType() == 2) {
            if (null != sellerOrderDetail.getSupperReturnPrice()) {
                sellerOrderDetail.setReturnCash(sellerOrderDetail.getSupperReturnPrice().doubleValue());
                sellerOrderDetail.setOrderPaymentAmount(sellerOrderDetail.getSupperPaymentAmount().toString());
            }
            if (null != sellerOrderDetail.getSupperRefundPrice()) {
                sellerOrderDetail.setReturnCash(sellerOrderDetail.getSupperRefundPrice().doubleValue());
                sellerOrderDetail.setOrderPaymentAmount(sellerOrderDetail.getSupperPaymentAmount().toString());
            }
            List<GoodsDetailsVO> goodsDetails = sellerOrderDetail.getGoodsDetails();
            if (!CollectionUtils.isEmpty(goodsDetails)){
                for (GoodsDetailsVO goodsDetail : goodsDetails) {
                    goodsDetail.setOrderGoodsPaymentAmount(sellerOrderDetail.getSupperPaymentAmount().doubleValue());
                }
            }
        }

        if (sellerOrderDetail.getReturnState() == 1) {
            sellerOrderDetail.setStepState(1);
        }
        if (sellerOrderDetail.getReturnState() == 2 || sellerOrderDetail.getReturnState() == 3) {
            sellerOrderDetail.setStepState(2);
        }
        if (sellerOrderDetail.getReturnState() == 6) {
            // 卖家收到货物
            sellerOrderDetail.setStepState(3);
        }
        if (sellerOrderDetail.getReturnState() == 4) {
            sellerOrderDetail.setStepState(4);
        }
        //退款关闭（新增的）
        if (sellerOrderDetail.getReturnState() == 8) {
            sellerOrderDetail.setStepState(8);
        }
        //平台介入（新增的）
        if (sellerOrderDetail.getReturnState() == 9) {
            sellerOrderDetail.setStepState(9);
        }
        //验收不通过（新增的）
        if (sellerOrderDetail.getReturnState() == 10) {
            sellerOrderDetail.setStepState(10);
        }
        //待买家退货（新增的）
        if (sellerOrderDetail.getReturnState() == 11) {
            sellerOrderDetail.setStepState(11);
        }
        //待验收（新增的）
        if (sellerOrderDetail.getReturnState() == 12) {
            sellerOrderDetail.setStepState(12);
        }
        return ResponseResult.success(sellerOrderDetail);
    }

    @Override
    public ResponseResult refundDetail(Map<String, String> map) {
        String returnCode = map.get("returnCode");
        SellerOrderDetailVO sellerOrderDetail = this.baseMapper.getSellerOrderDetailById(returnCode);
        if (sellerOrderDetail.getReturnState() == 1) {
            sellerOrderDetail.setStepState(1);
        }
        if (sellerOrderDetail.getReturnState() == 3 || sellerOrderDetail.getReturnState() == 4) {
            sellerOrderDetail.setStepState(2);
        }
        if (sellerOrderDetail.getReturnState() == 5) {
            sellerOrderDetail.setStepState(3);
        }
        return ResponseResult.success(sellerOrderDetail);
    }

    @Override
    public ResponseResult returnShipping(Map<String, String> paraMap) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
        }
        Map<String, Object> orderGoodsMap = new HashMap<>();
        String orderId = this.baseMapper.selectOne(new LambdaQueryWrapper<OrderReturnEntity>()
                .eq(OrderReturnEntity::getReturnCode, paraMap.get("returnCode"))).getOrderId();
        //查询退款详情
        ReturnOrderDetailVO returnOrderDetail = this.baseMapper.queryOrderReturnDetail(orderId);
        if (Integer.parseInt(returnOrderDetail.getReturnState()) == 10) {
            Integer resubmissionsNumber = returnOrderDetail.getResubmissionsNumber() + 1;
            orderGoodsMap.put("resubmissionsNumber", resubmissionsNumber);
        }

        orderGoodsMap.put("returnCode", paraMap.get("returnCode"));
        // 退货物流单号
        orderGoodsMap.put("returnShippingCode", paraMap.get("returnShippingCode"));
        // 联系电话
        orderGoodsMap.put("returnMobile", paraMap.get("returnMobile"));
        // 物流id
        orderGoodsMap.put("returnPostCode", paraMap.get("returnPostCode"));
        orderGoodsMap.put("returnShopHandle", 6);
        // 订单状态
        orderGoodsMap.put("returnState", "6");
        orderGoodsMap.put("callStatus", 0);
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        instance.add(Calendar.DATE, 7);
        Date instanceTime = instance.getTime();
        orderGoodsMap.put("expirationTime", instanceTime);

        Integer torf = this.baseMapper.updateOrderReturnById(orderGoodsMap);
        if (1 == torf) {
            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.FILLING_LOGISTICS_ERROR.getCode(), BizCodeEnume.FILLING_LOGISTICS_ERROR.getMsg());
    }

    // 申请售后时，不更改orderstatus
    @Transactional
    public ResponseResult onlyReturnMoney(Map<String, Object> paraMap, UserInfoVO userInfo) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            OrderBaseVO orderBase = orderBaseMapper.getOrderBaseById(paraMap.get("orderId").toString());
            //商家未操作之前，用户是可以操作的
//        if (orderBase.getOrderRefundStatus().equals(CommonType.orderRefundStatus.REFUNDING.getCode())) {
//            //当前订单退款中,请勿重复操作
//            return ResponseResult.fail(BizCodeEnume.CURRENT_ORDER_REFUND_IN_PROGRESS);
//        }
            Integer shopId = orderBase.getShopId();
            // 实付金额
            double orderPaymentMmount = orderBase.getOrderPaymentAmount().doubleValue();
            // 退款金额
            double returnCash = Double.parseDouble(paraMap.get("returnCash").toString());
            //售后商品id
            List<Integer> returnGoods = (List) paraMap.get("applyReturnGoods");
            // 如果订单售后时间小于当前时间订单不可退
            if (null != orderBase.getOrderLastReturnTime() && DateUtils.compareDate(orderBase.getOrderLastReturnTime(), DateUtils.getNowDate())) {
                return ResponseResult.fail(BizCodeEnume.ORDER_AFTER_TIME_EXCEED);
            }
            // 如果退款金额大于实付金额，取实付金额
            if (returnCash > orderPaymentMmount) {
                returnCash = orderPaymentMmount;
            }

            try {
                // sendMessage(shopId);
            } catch (Exception e) {
                return ResponseResult.fail(e.getMessage());
            } finally {
                //清空平台介入信息
                orderReturnPlatformMapper.delete(new LambdaQueryWrapper<OrderReturnPlatformEntity>()
                        .eq(OrderReturnPlatformEntity::getOrderId, String.valueOf(paraMap.get("orderId"))));

                // 去userms模块查找用户信息 "sellerId","sellerName","shopId","userId"
                Map<String, String> getSerllerInfoMap = new HashMap<>();
                getSerllerInfoMap.put("shopId", orderBase.getShopId().toString());
                Map<String, String> sellerInfo = (Map<String, String>) userServiceClient.getSellerInfo(getSerllerInfoMap).getData();

                Map<String, Object> orderBaseMap = new HashMap<>();
                orderBaseMap.put("orderStatus", 6);
                orderBaseMap.put("orderRefundStatus", 1);
                orderBaseMap.put("orderFinishedTime", DateUtils.getNowDate());
                orderBaseMap.put("orderId", paraMap.get("orderId"));
                orderBaseMap.put("orderRefundAmount", returnCash);
                orderBaseMap.put("returnMethodType", 2);
                // 填写卖家id，为资金回退做准备
                orderBaseMap.put("sellerUserId", sellerInfo.get("userId"));

                Integer one = orderBaseMapper.update(null, new LambdaUpdateWrapper<OrderBaseEntity>()
                        .eq(OrderBaseEntity::getOrderId, paraMap.get("orderId"))
                        .set(OrderBaseEntity::getOrderStatus, CommonType.orderStatus.CONFIRM_RECEIPT.getCode())
                        .set(OrderBaseEntity::getOrderRefundStatus, CommonType.orderRefundStatus.REFUNDING.getCode())
                        .set(OrderBaseEntity::getOrderFinishedTime, DateUtils.getNowDate())
                        .set(OrderBaseEntity::getReturnMethodType, CommonType.returnMethodType.ONLY_REFUND.getCode())
                        // 1.1 退回资金
                        .set(OrderBaseEntity::getOrderRefundAmount, returnCash)
                        // 插入买家id，为资金回退做准备
                        .set(OrderBaseEntity::getSellerUserId, sellerInfo.get("userId")));

                //由于要展示退货详情所以商品表撤销是没清状态(所以二次申请要清空状态)
                Map<String, Object> orderGoodsMap1 = new HashMap<String, Object>();
                orderGoodsMap1.put("goodsRefundStatus", 0);
                orderGoodsMap1.put("goodsReturnStatus", 0);
                orderGoodsMap1.put("orderId", paraMap.get("orderId"));
                this.baseMapper.updateOrderGoodsById(orderGoodsMap1);

                Map<String, Object> orderGoodsMap = new HashMap<String, Object>();
                Integer two = null;
                if (returnGoods != null && returnGoods.size() > 0) {
                    for (Integer returnGood : returnGoods) {
                        Integer returnnum = orderGoodsMapper.queryBuyNumByorderId1(String.valueOf(paraMap.get("orderId")), returnGood);
                        orderGoodsMap.put("goodsRefundStatus", 1);
                        orderGoodsMap.put("goodsReturnStatus", 0);
                        orderGoodsMap.put("orderGoodsStatus", 6);
                        orderGoodsMap.put("orderId", paraMap.get("orderId"));
                        orderGoodsMap.put("goodsId", returnGood);
                        orderGoodsMap.put("orderGoodsReturnnum", returnnum);
                        two = this.baseMapper.updateOrderGoodsById1(orderGoodsMap);
                    }
                }
                Map<String, Object> orderReturnMap = new HashMap<>();
                Integer isExistData = this.baseMapper.selectCount(new LambdaQueryWrapper<OrderReturnEntity>()
                        .eq(OrderReturnEntity::getOrderId, paraMap.get("orderId")));

                if (paraMap.get("returnVoucher") != null) {
                    List<String> complaintsImages = (List<String>) paraMap.get("returnVoucher");
                    String returnVoucher = JSON.toJSONString(complaintsImages);
                    orderReturnMap.put("returnVoucher", returnVoucher);
                }
                orderReturnMap.put("orderId", paraMap.get("orderId"));
                orderReturnMap.put("returnState", 1);
                orderReturnMap.put("returnShopHandle", 1);
                orderReturnMap.put("returnMethodStatus", 2);
                // 1为退款申请,2为退货申请
                orderReturnMap.put("returnType", 1);
                orderReturnMap.put("returnReasonId", paraMap.get("returnReasonId"));
                orderReturnMap.put("returnReason", paraMap.get("returnReason"));
                orderReturnMap.put("returnMessage", paraMap.get("returnMessage"));
                orderReturnMap.put("returnCash", returnCash);
                orderReturnMap.put("returnRptCash", orderBase.getOrderRptPrice());
                orderReturnMap.put("buyerUserId", userInfo.getUserId());
                orderReturnMap.put("shopId", orderBase.getShopId());
                orderReturnMap.put("shopName", orderBase.getShopName());
                orderReturnMap.put("buyerUserAccount", userInfo.getUserName());
                orderReturnMap.put("orderAmount", orderBase.getOrderGoodsAmount().doubleValue() + orderBase.getOrderShippingFee());
                orderReturnMap.put("orderGoodsId", "0");
                orderReturnMap.put("orderGoodsName", "0");
                orderReturnMap.put("orderGoodsPrice", "0");
                orderReturnMap.put("orderGoodsNum", "0");
                orderReturnMap.put("orderGoodsPic", "0");
                orderReturnMap.put("returnAddrId", 0);
                orderReturnMap.put("returnPostCode", 0);
                orderReturnMap.put("sellerUserId", sellerInfo.get("userId"));

                this.baseMapper.updateOdbOrderReturn(String.valueOf(paraMap.get("orderId")));
                if (isExistData == 1) {
                    OrderReturnStatusDTO returnStatus = this.baseMapper.queryOrderReturnData(String.valueOf(paraMap.get("orderId")));
                    // 存在更新数据
                    //在卖家没介入之前可以一直修改但不改失效时间
                    orderReturnMap.put("historicalReturnStatus", "");
                    if (returnStatus.getReturnState() != 1) {
                        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Calendar calendar = Calendar.getInstance();
                        String nowDate = DateUtils.getTime();
                        Date date = null;
                        try {
                            date = formatter1.parse(nowDate);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        calendar.setTime(date);
                        calendar.add(Calendar.DATE, 1);
                        //处理时效时间
                        Date calendarTime = calendar.getTime();
                        orderReturnMap.put("returnAddTime", nowDate);
                        orderReturnMap.put("expirationTime", formatter1.format(calendarTime));
                        Integer returnChangeNum = returnStatus.getReturnChangeNum() + 1;
                        orderReturnMap.put("returnChangeNum", returnChangeNum);
                    }
                    // 更新申请退款记录
                    boolean isUpdateReturnSuccess = this.baseMapper.updateOrderReturn(orderReturnMap);
                    System.out.println("-----isUpdateReturnSUccess-----" + isUpdateReturnSuccess);
                } else {
                    // 根据商品己算退货价格
                    orderReturnMap.put("orderId", paraMap.get("orderId"));

                    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
                    String dateString = formatter.format(new Date());
                    Date addTime = new Date();
                    Calendar instance = Calendar.getInstance();
                    instance.setTime(addTime);
                    instance.add(Calendar.DATE, 1);
                    Date expirationTime = instance.getTime();

                    String returnCode = "TD-" + userInfo.getUserId() + "-" + orderBase.getShopId() + "-" + dateString + "-"
                            + "0001";
                    // 退货编号
                    orderReturnMap.put("returnCode", returnCode);

                    orderReturnMap.put("returnAddTime", df.format(addTime));
                    orderReturnMap.put("expirationTime", df.format(expirationTime));

                    // 填写卖家id，为资金回退做准备
                    orderReturnMap.put("sellerUserId", sellerInfo.get("userId"));
                    orderReturnMap.put("returnMobile", orderBase.getOrderReceiverContact());
                    Integer three = this.baseMapper.insertOrderReturn(orderReturnMap);

                    if (1 != one || 0 == two || 1 != three) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return ResponseResult.fail();
                    }

                    // 使用feign在其他库插入数据
                    Map<String, String> userRecordMap = new HashMap<String, String>();
                    userRecordMap.put("orderId", String.valueOf(paraMap.get("orderId")));
                    userRecordMap.put("userId", userInfo.getUserId());
                    userRecordMap.put("userNickname", userInfo.getUserName());
                    userRecordMap.put("recordMoney", String.valueOf(returnCash));
                    userRecordMap.put("recordDate", DateUtils.getTime());
                    userRecordMap.put("recordYear", DateUtils.getYear());
                    userRecordMap.put("recordMonth", DateUtils.getMonth());
                    userRecordMap.put("recordDay", DateUtils.getDay());
                    userRecordMap.put("recordTitle", "退款");
                    userRecordMap.put("recordDesc", "订单号：" + paraMap.get("orderId"));
                    userRecordMap.put("recordTime", DateUtils.getTime());
                    userRecordMap.put("tradeTypeId", "5");
                    userRecordMap.put("userType", "1");
                    userRecordMap.put("recordStatus", "8");
                    userRecordMap.put("recordPayorder", orderBase.getPaymentNumber());
                    userRecordMap.put("recordPaytime", DateUtils.getTime());

                    Map<String, String> sellerRecordMap = new HashMap<String, String>();
                    sellerRecordMap.put("orderId", String.valueOf(paraMap.get("orderId")));
                    sellerRecordMap.put("userId", sellerInfo.get("userId"));
                    sellerRecordMap.put("userNickname", sellerInfo.get("sellerName"));
                    sellerRecordMap.put("recordMoney", String.valueOf(returnCash));
                    sellerRecordMap.put("recordDate", DateUtils.getTime());
                    sellerRecordMap.put("recordYear", DateUtils.getYear());
                    sellerRecordMap.put("recordMonth", DateUtils.getMonth());
                    sellerRecordMap.put("recordDay", DateUtils.getDay());
                    sellerRecordMap.put("recordTitle", "退款");
                    sellerRecordMap.put("recordDesc", "订单号：" + paraMap.get("orderId"));
                    sellerRecordMap.put("recordTime", DateUtils.getTime());
                    sellerRecordMap.put("tradeTypeId", "5");
                    sellerRecordMap.put("userType", "2");
                    sellerRecordMap.put("recordStatus", "8");
                    sellerRecordMap.put("recordPayorder", orderBase.getPaymentNumber());
                    sellerRecordMap.put("recordPaytime", DateUtils.getTime());

                    Map<String, Map<String, String>> returnMap = new HashMap<String, Map<String, String>>();
                    returnMap.put("user", userRecordMap);
                    returnMap.put("seller", sellerRecordMap);
                    ResponseResult torf = payMentServiceClient.insertRecord(returnMap);

                    //发送站内信
                    String content = "您的会员" + userInfo.getUserName() + "提交了退款申请，请尽快处理";
                    orderComplaintsMapper.insertSysMessage1("", orderBase.getSellerUserId(),"",9,
                            "用户提交退款",content, String.valueOf(orderBase.getShopId()));

                    if (CommonStatusEnum.SUCCESS.getCode() != torf.getCode()) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return ResponseResult.fail();
                    }
                }
            }
        } catch (Exception e) {
            return ResponseResult.fail(e.getMessage());
        }

        return ResponseResult.success(BizCodeEnume.APPLICATION_SUCCESS);
    }

    /**
     * 1.1 将退款价格改为去掉优惠价格（红包，代金券）
     * 1.2 申请售后时不修改 orderstatus
     *
     * @param paraMap
     * @param userInfo
     * @return
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult applyReturn(Map<String, String> paraMap, UserInfoVO userInfo) throws TransactionException {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 将double类型数据转为两位小数
            DecimalFormat decimalFormat = new DecimalFormat("#.00");
            OrderBaseVO orderBase = orderBaseMapper.getOrderBaseById(paraMap.get("orderId"));
            if (orderBase.getOrderReturnStatus().equals(CommonType.orderReturnStatus.RETURNING_GOODS.getCode())) {
                //当前订单退货中,请勿重复操作
                return ResponseResult.fail(BizCodeEnume.CURRENT_ORDER_RETURN_IN_PROGRESS);
            }
            // 如果订单售后时间小于当前时间订单不可退
            if (null != orderBase.getOrderLastReturnTime() && DateUtils.compareDate(orderBase.getOrderLastReturnTime(), DateUtils.getNowDate())) {
                return ResponseResult.fail(BizCodeEnume.ORDER_AFTER_TIME_EXCEED);
            }
            // 去userms模块查找用户信息 "sellerId","sellerName","shopId","userId"
            Map<String, String> getSerllerInfoMap = new HashMap<>();
            getSerllerInfoMap.put("shopId", orderBase.getShopId().toString());
            Map<String, String> sellerInfo = (Map<String, String>) userServiceClient.getSellerInfo(getSerllerInfoMap).getData();

            // 根据商品己算退货价格，减去红包和代金券价格
            Double returnCash = Double.parseDouble(paraMap.get("orderGoodsNum"))
                    * Double.parseDouble(paraMap.get("orderGoodsPrice"));
            Double proportional = returnCash / orderBase.getOrderGoodsAmount().doubleValue();
            returnCash = orderBase.getOrderPaymentAmount().doubleValue() * proportional;

            Integer one = orderBaseMapper.update(null, new LambdaUpdateWrapper<OrderBaseEntity>()
                    .eq(OrderBaseEntity::getOrderId, paraMap.get("orderId"))
                    .set(OrderBaseEntity::getOrderReturnStatus, CommonType.orderReturnStatus.RETURNING_GOODS.getCode())
                    .set(OrderBaseEntity::getOrderRefundAmount, orderBase.getOrderPaymentAmount())
                    // 插入买家id，为资金回退做准备
                    .set(OrderBaseEntity::getSellerUserId, sellerInfo.get("userId"))
                    .set(OrderBaseEntity::getOrderFinishedTime, DateUtils.getNowDate()));


            Integer two = orderGoodsMapper.update(null, new LambdaUpdateWrapper<OrderGoodsEntity>()
                    .eq(OrderGoodsEntity::getOrderId, paraMap.get("orderId"))
                    .set(OrderGoodsEntity::getOrderGoodsReturnnum, paraMap.get("orderGoodsNum"))
                    .set(OrderGoodsEntity::getGoodsRefundStatus, CommonType.orderRefundStatus.REFUNDING.getCode()));

            Map<String, Object> orderReturnMap = new HashMap<>();

            orderReturnMap.put("orderId", paraMap.get("orderId"));
            // 订单总额
            orderReturnMap.put("orderAmount", orderBase.getOrderGoodsAmount());
            // ，不包含运费
            orderReturnMap.put("orderGoodsId", paraMap.get("orderGoodsId"));
            orderReturnMap.put("orderGoodsName", paraMap.get("orderGoodsName"));
            orderReturnMap.put("orderGoodsPrice", paraMap.get("orderGoodsPrice"));
            orderReturnMap.put("orderGoodsNum", paraMap.get("orderGoodsNum"));
            orderReturnMap.put("orderGoodsPic", paraMap.get("orderGoodsPic"));

            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String dateString = formatter.format(new Date());
            String returnCode = "TD-" + userInfo.getUserId() + "-" + orderBase.getShopId() + "-" + dateString + "-"
                    + "0001";
            // 退货编号
            orderReturnMap.put("returnCode", returnCode);
            // 1为退款申请,2为退货申请
            orderReturnMap.put("returnType", "2");
            orderReturnMap.put("buyerUserId", userInfo.getUserId());
            orderReturnMap.put("shopId", orderBase.getShopId());
            orderReturnMap.put("shopName", orderBase.getShopName());
            orderReturnMap.put("buyerUserAccount", userInfo.getUserName());
            orderReturnMap.put("returnAddTime", df.format(new Date()));
            orderReturnMap.put("returnReasonId", paraMap.get("returnReasonId"));
            orderReturnMap.put("returnReason", paraMap.get("returnReason"));
            orderReturnMap.put("returnMessage", paraMap.get("returnMessage"));
            orderReturnMap.put("returnAddrId", 0);
            orderReturnMap.put("returnPostCode", 0);
            // 1-新发起等待卖家审核 2-卖家审核通过 3-卖家审核不通过
            orderReturnMap.put("returnState", 1);
            // 4-卖家收到货物 5-平台审核通过',
            orderReturnMap.put("returnCash", returnCash);
            // 待写红包分担金额
            orderReturnMap.put("returnRptCash",
                    decimalFormat.format(returnCash / orderBase.getOrderGoodsAmount().doubleValue() * orderBase.getOrderRptPrice()));
            orderReturnMap.put("returnShopHandle", 1);
            // 插入买家id，为资金回退做准备
            orderReturnMap.put("sellerUserId", sellerInfo.get("sellerId"));

            int three = insertOrderReturn(paraMap.get("orderId"), orderBase.getOrderGoodsAmount().doubleValue(), paraMap.get("orderGoodsId"), paraMap.get("orderGoodsName"), paraMap.get("orderGoodsPrice"), paraMap.get("orderGoodsNum"), paraMap.get("orderGoodsPic"),
                    "2", userInfo, orderBase, sellerInfo,
                    paraMap.get("returnReasonId"), paraMap.get("returnReason"), paraMap.get("returnMessage"),
                    returnCash, returnCash / orderBase.getOrderGoodsAmount().doubleValue() * orderBase.getOrderRptPrice(), null);

            if (1 != one || 0 == two || 1 != three) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseResult.fail();
            }

            // 使用feign在其他库插入数据
            ResponseResult torf = insertRecord(paraMap.get("orderId"), userInfo, String.valueOf(returnCash), orderBase.getPaymentNumber(), sellerInfo);

            if (CommonStatusEnum.SUCCESS.getCode() != torf.getCode()) {
                GlobalTransactionContext.reload(RootContext.getXID()).rollback();
                return ResponseResult.fail();
            }
        } catch (Exception e) {
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            return ResponseResult.fail(e.getMessage());
        }
        return ResponseResult.success(BizCodeEnume.APPLICATION_SUCCESS);
    }

    private int insertOrderReturn(String orderId, double orderAmount, String orderGoodsId,
                                  String orderGoodsName, String orderGoodsPrice, String orderGoodsNum, String orderGoodsPic,
                                  String returnType,
                                  UserInfoVO userInfo, OrderBaseVO orderBase, Map<String, String> sellerInfo,
                                  String returnReasonId, String returnReason, String returnMessage,
                                  double returnCash, double returnRptCash, String returnShippingFee) {
        Map<String, Object> orderReturnMap = new HashMap<String, Object>();
        // 不存在创建数据
        orderReturnMap.put("orderId", orderId);
        // 订单总额
        orderReturnMap.put("orderAmount", orderAmount);
        orderReturnMap.put("orderGoodsId", orderGoodsId);
        orderReturnMap.put("orderGoodsName", orderGoodsName);
        orderReturnMap.put("orderGoodsPrice", orderGoodsPrice);
        orderReturnMap.put("orderGoodsNum", orderGoodsNum);
        orderReturnMap.put("orderGoodsPic", orderGoodsPic);

        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(new Date());
        String returnCode = "TD-" + userInfo.getUserId() + "-" + orderBase.getShopId() + "-" + dateString + "-"
                + "0001";
        // 退货编号
        orderReturnMap.put("returnCode", returnCode);
        // 1为退款申请,2为退货申请
        orderReturnMap.put("returnType", returnType);

        orderReturnMap.put("buyerUserId", userInfo.getUserId());
        orderReturnMap.put("shopId", orderBase.getShopId());
        orderReturnMap.put("shopName", orderBase.getShopName());
        orderReturnMap.put("buyerUserAccount", userInfo.getUserName());
        orderReturnMap.put("returnAddTime", DateUtils.getNowDate());
        orderReturnMap.put("returnReasonId", returnReasonId);
        orderReturnMap.put("returnReason", returnReason);
        orderReturnMap.put("returnMessage", returnMessage);

        orderReturnMap.put("returnAddrId", 0);
        orderReturnMap.put("returnPostCode", 0);
        // 1-新发起等待卖家审核 2-卖家审核通过 3-卖家审核不通过
        orderReturnMap.put("returnState", 1);
        orderReturnMap.put("returnShopHandle", 1);

        // 1.1 退回资金 = 应付金额（商品实际支付金额 + 运费）' - 运费
        orderReturnMap.put("returnCash", returnCash);
        orderReturnMap.put("returnRptCash", returnRptCash);
        orderReturnMap.put("returnShippingFee", returnShippingFee);

        // 插入买家id，为资金回退做准备
        orderReturnMap.put("sellerUserId", sellerInfo.get("userId"));
        orderReturnMap.put("returnMobile", orderBase.getOrderReceiverContact());
        Integer three = this.baseMapper.insertOrderReturn(orderReturnMap);
        return three;
    }

    /**
     * 使用feign在其他库插入数据
     *
     * @param orderId
     * @param userInfo
     * @param recordMoney
     * @param recordPayorder
     * @param sellerInfo
     * @return
     */
    private ResponseResult insertRecord(String orderId, UserInfoVO userInfo, String recordMoney, String recordPayorder, Map<String, String> sellerInfo) {

        // 使用feign在其他库插入数据
        Map<String, String> userRecordMap = new HashMap<>();
        userRecordMap.put("orderId", orderId);
        userRecordMap.put("userId", userInfo.getUserId());
        userRecordMap.put("userNickname", userInfo.getUserName());
        userRecordMap.put("recordMoney", recordMoney);
        userRecordMap.put("recordDate", DateUtils.getNowDateToString());
        userRecordMap.put("recordYear", DateUtils.getYear());
        userRecordMap.put("recordMonth", DateUtils.getMonth());
        userRecordMap.put("recordDay", DateUtils.getDay());
        userRecordMap.put("recordTitle", "退款");
        userRecordMap.put("recordDesc", "订单号：" + orderId);
        userRecordMap.put("recordTime", DateUtils.getNowDateToString());
        userRecordMap.put("tradeTypeId", "5");
        userRecordMap.put("userType", "1");
        userRecordMap.put("recordStatus", "8");
        userRecordMap.put("recordPayorder", recordPayorder);
        userRecordMap.put("recordPaytime", DateUtils.getNowDateToString());

        Map<String, String> sellerRecordMap = new HashMap<>();
        sellerRecordMap.put("orderId", orderId);
        sellerRecordMap.put("userId", sellerInfo.get("userId"));
        sellerRecordMap.put("userNickname", sellerInfo.get("sellerName"));
        sellerRecordMap.put("recordMoney", recordMoney);
        sellerRecordMap.put("recordDate", DateUtils.getNowDateToString());
        sellerRecordMap.put("recordYear", DateUtils.getYear());
        sellerRecordMap.put("recordMonth", DateUtils.getMonth());
        sellerRecordMap.put("recordDay", DateUtils.getDay());
        sellerRecordMap.put("recordTitle", "退款");
        sellerRecordMap.put("recordDesc", "订单号：" + orderId);
        sellerRecordMap.put("recordTime", DateUtils.getNowDateToString());
        sellerRecordMap.put("tradeTypeId", "5");
        sellerRecordMap.put("userType", "2");
        sellerRecordMap.put("recordStatus", "8");
        sellerRecordMap.put("recordPayorder", recordPayorder);
        sellerRecordMap.put("recordPaytime", DateUtils.getNowDateToString());

        Map<String, Map<String, String>> returnMap = new HashMap<String, Map<String, String>>();
        returnMap.put("user", userRecordMap);
        returnMap.put("seller", sellerRecordMap);
        ResponseResult result = payMentServiceClient.insertRecord(returnMap);
        return result;
    }

    /**
     * 1.1 将退款时钱是商品总价 改为去掉优惠信息价格 申请退款
     * 1.2 申请售后时不更新orderstatus
     *
     * @param paraMap
     * @param userInfo
     * @return
     */
    public ResponseResult applyRefund(Map<String, String> paraMap, UserInfoVO userInfo) {
        OrderBaseVO orderBase = orderBaseMapper.getOrderBaseById(paraMap.get("orderId"));
        if (orderBase.getPayCode() == 14 && userInfo.getIsEmployee() == 1) {
            ResponseResult result = userServiceClient.queryUserInfoByUserId(userInfo.getCreateUser());
            userInfo = JSON.parseObject((String) result.getData(), UserInfoVO.class);
        }
        Integer shopId = orderBase.getShopId();

        Integer orderStatus = orderBase.getOrderStatus();
        //虚拟商品 0 是 1 否
        Integer virtualGoods = orderBase.getVirtualGoods();

        //代发货状态下的 虚拟订单  和 自提订单 可以申请退款 //非门店自提的实物订单在商家发货前可以申请退款
        if (null != orderStatus && 4 == orderStatus && (null == orderBase.getVirtualGoods() || 1 == orderBase.getVirtualGoods()) && (2 == orderBase.getOrderIsShopTake())) {
            return ResponseResult.fail();
        }
        //虚拟订单
        if (null != virtualGoods && 0 == virtualGoods) {
            boolean virtualFlag = checkVirtualGoods(paraMap, orderStatus);
            if (!virtualFlag) {
                return ResponseResult.fail(0, "该虚拟商品已过期,无法退款");
            }
        }

        //清空平台介入信息
        orderReturnPlatformMapper.delete(new LambdaQueryWrapper<OrderReturnPlatformEntity>().eq(OrderReturnPlatformEntity::getOrderId, String.valueOf(paraMap.get("orderId"))));

        // 去userms模块查找用户信息 "sellerId","sellerName","shopId","userId"
        Map<String, String> getSerllerInfoMap = new HashMap<>();
        getSerllerInfoMap.put("shopId", orderBase.getShopId().toString());
        Map<String, String> sellerInfo = (Map<String, String>) userServiceClient.getSellerInfo(getSerllerInfoMap).getData();


        Integer one = orderBaseMapper.update(null, new LambdaUpdateWrapper<OrderBaseEntity>()
                .eq(OrderBaseEntity::getOrderId, paraMap.get("orderId"))
                .set(OrderBaseEntity::getOrderRefundStatus, CommonType.orderRefundStatus.REFUNDING.getCode())
                // 1.1 退回资金 = 应付金额（商品实际支付金额 + 运费）' - 运费
                .set(OrderBaseEntity::getOrderRefundAmount, orderBase.getOrderPaymentAmount())
                // 插入买家id，为资金回退做准备
                .set(OrderBaseEntity::getSellerUserId, sellerInfo.get("userId")));


        Integer two = orderGoodsMapper.update(null, new LambdaUpdateWrapper<OrderGoodsEntity>()
                .eq(OrderGoodsEntity::getOrderId, paraMap.get("orderId"))
                .set(OrderGoodsEntity::getOrderGoodsStatus, CommonType.orderStatus.CONFIRM_RECEIPT.getCode())
                .set(OrderGoodsEntity::getGoodsRefundStatus, CommonType.orderRefundStatus.REFUNDING.getCode()));
        Integer orderGoodsNum = 0;
        //查询订单商品数量
        List<OrderGoodsEntity> goodsNumList = orderGoodsMapper.selectList(new LambdaQueryWrapper<OrderGoodsEntity>()
                .eq(OrderGoodsEntity::getOrderId, paraMap.get("orderId")));

        if (null != goodsNumList) {
            for (OrderGoodsEntity orderGoods : goodsNumList) {
                Integer goodsId = orderGoods.getGoodsId();
                Integer goodsNum = Integer.parseInt(orderGoods.getOrderGoodsNum());
                orderGoodsNum += goodsNum;
                //修改订单退款数量
                orderGoodsMapper.update(null, new LambdaUpdateWrapper<OrderGoodsEntity>()
                        .eq(OrderGoodsEntity::getGoodsId, goodsId)
                        .set(OrderGoodsEntity::getOrderGoodsReturnnum, goodsNum));
            }

        }
        //如果是 供应商代发货的订单 查询供应商的商品价格 计算退单金额
        //因为 同步是商品不能加购物车 所以 退货数量 和 退货商品价格是唯一
        if (null != orderBase.getDropShipping() && 1 == orderBase.getDropShipping()) {
            BigDecimal supperReturnPrice = new BigDecimal(0);
            supperReturnPrice = orderBase.getGoodsPaymentAmount();
            OrderSupplierBaseEntity orderSupplierOrderBaseEntity = orderSupplierBaseService.getById(paraMap.get("orderId"));
            //将退单的供应商 退款金额存入数据库
            orderSupplierBaseService.update(null, new LambdaUpdateWrapper<OrderSupplierBaseEntity>()
                    .set(OrderSupplierBaseEntity::getOrderRefundPrice, supperReturnPrice)
                    //修改退款佣金
                    .set(OrderSupplierBaseEntity::getSupperReturnCommission, orderSupplierOrderBaseEntity.getSupperCommission()));


        }
        // 查询是否存在该条数据
        Map<String, Object> orderReturnMap = new HashMap<>();
        Integer isExistData = this.baseMapper.selectCount(new LambdaQueryWrapper<OrderReturnEntity>()
                .eq(OrderReturnEntity::getOrderId, paraMap.get("orderId")));
        this.baseMapper.updateOdbOrderReturn(paraMap.get("orderId"));

        orderReturnMap.put("orderId", paraMap.get("orderId"));
        orderReturnMap.put("returnState", 1);
        orderReturnMap.put("returnShopHandle", 1);
        orderReturnMap.put("returnType", 1);
        orderReturnMap.put("returnMethodStatus", 1);
        orderReturnMap.put("returnReasonId", paraMap.get("returnReasonId"));
        orderReturnMap.put("returnReason", paraMap.get("returnReason"));
        orderReturnMap.put("returnMessage", paraMap.get("returnMessage"));
        orderReturnMap.put("returnCash", orderBase.getOrderPaymentAmount());
        // 订单总额
        orderReturnMap.put("orderAmount", orderBase.getOrderGoodsAmount());
        orderReturnMap.put("orderGoodsId", 0);
        orderReturnMap.put("orderGoodsName", 0);
        orderReturnMap.put("orderGoodsPrice", 0);
        orderReturnMap.put("orderGoodsNum", orderGoodsNum);
        orderReturnMap.put("orderGoodsPic", 0);
        orderReturnMap.put("buyerUserId", userInfo.getUserId());
        orderReturnMap.put("shopId", orderBase.getShopId());
        orderReturnMap.put("shopName", orderBase.getShopName());
        orderReturnMap.put("buyerUserAccount", userInfo.getUserName());
        orderReturnMap.put("returnAddrId", 0);
        orderReturnMap.put("returnPostCode", 0);
        // 4-卖家收到货物 5-平台审核通过',
        BigDecimal orderPaymentAmount = orderBase.getOrderPaymentAmount();
        // 1.1 退回资金 = 应付金额（商品实际支付金额 + 运费）' - 运费
        orderReturnMap.put("returnCash", orderPaymentAmount);
        orderReturnMap.put("returnRptCash", orderBase.getOrderRptPrice());
        orderReturnMap.put("returnShopHandle", 1);
        orderReturnMap.put("returnMethodStatus", 1);
        orderReturnMap.put("returnMobile", orderBase.getOrderReceiverContact());

        // 插入买家id，为资金回退做准备
        orderReturnMap.put("sellerUserId", sellerInfo.get("userId"));
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //创建时间
        Calendar calendar = Calendar.getInstance();
        String nowDate = DateUtils.getTime();
        Date date = null;
        try {
            date = formatter1.parse(nowDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.setTime(date);
        calendar.add(Calendar.DATE, 1);
        //处理时效时间
        Date calendarTime = calendar.getTime();
        orderReturnMap.put("returnAddTime", nowDate);

        if (isExistData == 1) {
            OrderReturnStatusDTO returnStatus = this.baseMapper.queryOrderReturnData(paraMap.get("orderId"));
            // 存在更新数据
            //在卖家没介入之前可以一直修改但不改失效时间
            orderReturnMap.put("historicalReturnStatus", "");
            if (null != returnStatus.getReturnState() && returnStatus.getReturnState() != 1 && returnStatus.getReturnState() != 15) {
                Integer returnChangeNum = returnStatus.getReturnChangeNum() + 1;
                orderReturnMap.put("returnChangeNum", returnChangeNum);
                orderReturnMap.put("expirationTime", formatter1.format(calendarTime));
            }else if(returnStatus.getReturnState() == 15){
                orderReturnMap.put("expirationTime", formatter1.format(calendarTime));
            }

            // 更新申请退款记录
            boolean isUpdateReturnSuccess = this.baseMapper.updateOrderReturn(orderReturnMap);

        } else {
            //处理时效时间
            orderReturnMap.put("expirationTime", formatter1.format(calendarTime));
            // 不存在创建数据
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String dateString = formatter.format(new Date());
            String returnCode = "TD-" + userInfo.getUserId() + "-" + orderBase.getShopId() + "-" + dateString + "-"
                    + "0001";
            // 退货编号
            orderReturnMap.put("returnCode", returnCode);
            Integer three = this.baseMapper.insertOrderReturn(orderReturnMap);
            // two有可能为2
            if (1 != one || 0 == two || 1 != three) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseResult.fail();
            }

            Map<String, Map<String, String>> returnMap = setOrderReturnInfo(paraMap, userInfo, orderBase, orderPaymentAmount, sellerInfo);
            ResponseResult tort = payMentServiceClient.insertRecord(returnMap);
            //发送站内信
            String content = "您的会员" + userInfo.getUserName() + "提交了退款申请，请尽快处理";
            orderComplaintsMapper.insertSysMessage1("", orderBase.getSellerUserId(),"",9,
                    "用户提交退款",content, String.valueOf(orderBase.getShopId()));

            if (CommonStatusEnum.SUCCESS.getCode() != tort.getCode()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseResult.fail();
            }
        }
        return ResponseResult.success();

    }

    /**
     * @return boolean
     * @Author Dark Wang
     * @Description 查看虚拟订单是否可以退款，可以退款返回true,不能退款返回flase
     * @Date 14:34 2022/2/24
     * @Param [orderBase, paraMap]
     **/
    private boolean checkVirtualGoods(Map<String, String> paraMap, Integer orderStatus) {
        Map<Object, Object> map = orderGoodsMapper.getVitualInfo(paraMap.get("orderId"));
        //是否过了有效期 是:true,否:false
        boolean dueFlag = false;
        if (null != map.get("period_of_validity")) {
            Date date = DateUtils.parseCNDate(map.get("period_of_validity").toString().replace("T", " "));
            Date nowDate = new Date();
            Calendar calDue = Calendar.getInstance();
            Calendar calNow = Calendar.getInstance();
            calDue.setTime(date);
            calNow.setTime(nowDate);
            if (calNow.after(calDue)) {
                dueFlag = true;
            }
        }
        //过了有效期
        if (dueFlag) {
            return null != map.get("past_due") && 0 == (Integer) map.get("past_due");
            //没过有效期
        } else {
            return orderStatus >= 2 && orderStatus < 6;
        }
    }


    /**
     * 设置fegin参数
     *
     * @param paraMap
     * @param userInfo
     * @param orderBase
     * @param orderPaymentAmount
     * @param sellerInfo
     * @return
     */
    private Map<String, Map<String, String>> setOrderReturnInfo(Map<String, String> paraMap, UserInfoVO userInfo,
                                                                OrderBaseVO orderBase, BigDecimal orderPaymentAmount,
                                                                Map<String, String> sellerInfo) {
        // 使用feign在其他库插入数据
        Map<String, String> userRecordMap = new HashMap<>();
        userRecordMap.put("orderId", paraMap.get("orderId"));
        userRecordMap.put("userId", userInfo.getUserId());
        userRecordMap.put("userNickname", userInfo.getUserName());
        userRecordMap.put("recordMoney", String.valueOf(orderPaymentAmount));
        userRecordMap.put("recordDate", DateUtils.getTime());
        userRecordMap.put("recordYear", DateUtils.getYear());
        userRecordMap.put("recordMonth", DateUtils.getMonth());
        userRecordMap.put("recordDay", DateUtils.getDay());
        userRecordMap.put("recordTitle", "退款");
        userRecordMap.put("recordDesc", "订单号：" + paraMap.get("orderId"));
        userRecordMap.put("recordTime", DateUtils.getTime());
        userRecordMap.put("tradeTypeId", "5");
        userRecordMap.put("userType", "1");
        userRecordMap.put("recordStatus", "8");
        userRecordMap.put("recordPayorder", orderBase.getPaymentNumber());
        userRecordMap.put("recordPaytime", DateUtils.getTime());

        Map<String, String> sellerRecordMap = new HashMap<>();
        sellerRecordMap.put("orderId", paraMap.get("orderId"));
        sellerRecordMap.put("userId", sellerInfo.get("userId"));
        sellerRecordMap.put("userNickname", sellerInfo.get("sellerName"));
        sellerRecordMap.put("recordMoney", "-" + orderPaymentAmount);
        sellerRecordMap.put("recordDate", DateUtils.getTime());
        sellerRecordMap.put("recordYear", DateUtils.getYear());
        sellerRecordMap.put("recordMonth", DateUtils.getMonth());
        sellerRecordMap.put("recordDay", DateUtils.getDay());
        sellerRecordMap.put("recordTitle", "退款");
        sellerRecordMap.put("recordDesc", "订单号：" + paraMap.get("orderId"));
        sellerRecordMap.put("recordTime", DateUtils.getTime());
        sellerRecordMap.put("tradeTypeId", "5");
        sellerRecordMap.put("userType", "2");
        sellerRecordMap.put("recordStatus", "8");
        sellerRecordMap.put("recordPayorder", orderBase.getPaymentNumber());
        sellerRecordMap.put("recordPaytime", DateUtils.getTime());

        Map<String, Map<String, String>> returnMap = new HashMap<>();
        returnMap.put("user", userRecordMap);
        returnMap.put("seller", sellerRecordMap);
        return returnMap;
    }


    @Override
    public ResponseResult selectordereturn(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        String orderId = String.valueOf(map.get("orderId"));
        //查询退款详情
        ReturnOrderDetailVO returnOrderDetail = this.baseMapper.queryOrderReturnDetail(orderId);
        if (returnOrderDetail != null) {
            if(null == returnOrderDetail.getReturnAddr()){
                //赋值该订单发货地址
                String address = this.baseMapper.queryOrderAddress(returnOrderDetail.getOrderId());
                returnOrderDetail.setReturnAddr(address);
            }
            //获取商家拒绝次数
            if (RedisUtil.exists(YFConfig.NUMBER_OF_TIMES_MERCHANTS_REFUSE_REFUNDS + "-" + orderId)) {
                Integer number = Integer.valueOf(RedisUtil.getNoExpire(YFConfig.NUMBER_OF_TIMES_MERCHANTS_REFUSE_REFUNDS + "-" + orderId));
                if (number >= 3) {
                    //拒绝是否超过3次
                    returnOrderDetail.setNumberOfTimesMerchantsRefuseRefunds(CommonType.commonStatus.YES.getCode());
                } else {
                    returnOrderDetail.setNumberOfTimesMerchantsRefuseRefunds(CommonType.commonStatus.NO.getCode());
                }

            } else {
                returnOrderDetail.setNumberOfTimesMerchantsRefuseRefunds(CommonType.commonStatus.NO.getCode());
            }
            if (returnOrderDetail.getReturnVoucher() != null) {
                String returnVoucher = returnOrderDetail.getReturnVoucher();
                List<String> images = JSONArray.parseArray(returnVoucher, String.class);
                returnOrderDetail.setReturnVouchers(images);
                returnOrderDetail.setReturnVoucher(null);
            }
        } else {
            OrderBaseEntity entity=orderBaseMapper.selectById(orderId);
            if(null!=entity){
                Date now = new Date();
                int result = now.compareTo(entity.getPeriodOfValidity());
                if(entity.getVirtualGoods().equals(CommonType.commonStatus.NO.getCode())&&result>0){
                    return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INVENTED_ORDER_IS_OVERDUE.getMsg()+"不可退款");
                }
            }

            return ResponseResult.fail(BizCodeEnume.ORDER_AFTER_SALES_NULL);
        }
        //查询售后商品
        List<GoodsDetailsListVO> orderGoods = orderGoodsMapper.queryGoodsList1(orderId);
        returnOrderDetail.setOrderGoodsDetail(orderGoods);
        return ResponseResult.success(returnOrderDetail);
    }

    @Override
    public ResponseResult revokeIntervention(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        Map<String, Object> orderGoodsMap = new HashMap<String, Object>();
        String orderId = String.valueOf(map.get("orderId"));
        ReturnOrderDetailVO returnOrderDetail = this.baseMapper.queryOrderReturnDetail(orderId);
        Integer methodStatus = returnOrderDetail.getReturnMethodStatus();
        OrderReturnPlatformVO orderReturnPlatform = new OrderReturnPlatformVO();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        Date Application_time = calendar.getTime();
        calendar.add(Calendar.DATE, 1);
        Date calendarTime = calendar.getTime();
        orderReturnPlatform.setOrderId(orderId);

        // 买家撤销

        orderGoodsMap.put("returnCode", map.get("returnCode"));
        orderGoodsMap.put("historicalReturnStatus", returnOrderDetail.getReturnState());
        orderGoodsMap.put("returnShopHandle", 0);
        //退款方式:1.退款 2.仅退款 3退货退款
        if (methodStatus == 1 || methodStatus == 2) {
            //用户撤销退款关闭
            orderGoodsMap.put("returnState", 15);
        } else if (methodStatus == 3) {
            orderGoodsMap.put("returnState", 16);
        }
        orderGoodsMap.put("revokeNum", 1);
        orderGoodsMap.put("closeTime", new Date());

        Map<String, Object> updateMap = new HashMap<>();
        Map<String, Object> updateGoodsMap = new HashMap<>();
        Integer torfOne = null;
        Integer torfTwo = null;
        updateMap.put("orderId", orderId);
        // 原值：2，现改为0，用户可持续申请
        updateMap.put("orderRefundStatus", "0");
        // 原值：2，现改为0，用户可持续申请
        updateMap.put("orderReturnStatus", "0");

        updateGoodsMap.put("orderId", orderId);

        updateGoodsMap.put("goodsReturnStatus", 0);
        updateGoodsMap.put("goodsRefundStatus", 0);
        //添加商家拒绝退款时间
        String businessTime = String.valueOf(System.currentTimeMillis());
        String businessRefundTime = DateUtils.stampToDate(businessTime);

        torfOne = orderBaseMapper.updateOrderBaseById(updateMap);

        //更新record表状态
        Map<String, String> feignMap = new HashMap<>();
        feignMap.put("orderId", orderId);
        // 原值：7
        feignMap.put("recordStatus", "7");
        payMentServiceClient.updateRefuse(feignMap);

        if (1 != torfOne) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail();
        }
        Integer torf = this.baseMapper.updateOrderReturnById(orderGoodsMap);
        if (torf > 0) {
            return ResponseResult.success();
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult selectordereturnplatform(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
        }
        String orderId = String.valueOf(map.get("orderId"));
        //查询退款详情
        ReturnOrderDetailVO returnOrderDetail = this.baseMapper.queryOrderReturnDetail(orderId);
        if (returnOrderDetail != null) {
            if (returnOrderDetail.getReturnVoucher() != null) {
                String returnVoucher = returnOrderDetail.getReturnVoucher();
                List<String> imgs = JSONArray.parseArray(returnVoucher, String.class);
                returnOrderDetail.setReturnVouchers(imgs);
                returnOrderDetail.setReturnVoucher(null);
            }
        }
        if(null == returnOrderDetail.getReturnAddr() || null == returnOrderDetail.getReturnAddrName()){
            returnOrderDetail.setReturnAddr(this.baseMapper.queryOrderAddress(returnOrderDetail.getOrderId()));
            returnOrderDetail.setReturnAddrName(this.baseMapper.queryOrderAddrName(returnOrderDetail.getOrderId()));
        }
        //查询售后商品
        List<GoodsDetailsListVO> orderGoods = orderGoodsMapper.queryGoodsList1(orderId);
        returnOrderDetail.setOrderGoodsDetail(orderGoods);
        //查询平台介入
        OrderReturnPlatformVO orderReturnPlatform = orderReturnPlatformMapper.selectOrderReturnPlatform(orderId);
        if(orderReturnPlatform == null){
            orderReturnPlatform = new OrderReturnPlatformVO();
        }
        orderReturnPlatform.setOrderId(returnOrderDetail.getOrderId());
        returnOrderDetail.setInterventionState(orderReturnPlatform.getInterventionState());
        String buyer_voucher = orderReturnPlatform.getBuyerVoucher();
        String seller_voucher = orderReturnPlatform.getSellerVoucher();
        if (seller_voucher != null) {
            List<String> image = JSONArray.parseArray(seller_voucher, String.class);
            orderReturnPlatform.setSellerVouchers(image);
            orderReturnPlatform.setSellerVoucher(null);
        }
        if (buyer_voucher != null) {
            List<String> image = JSONArray.parseArray(buyer_voucher, String.class);
            orderReturnPlatform.setBuyerVouchers(image);
            orderReturnPlatform.setBuyerVoucher(null);
        }
        orderReturnPlatform.setReturnOrderDetail(returnOrderDetail);
        return ResponseResult.success(orderReturnPlatform);
    }

    @Override
    public ResponseResult checkAfterSales(Map<String, Object> map) {
        ResponseResult result = new ResponseResult();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
        }
        ReturnOrderDetailVO returnOrderDetail = this.baseMapper.queryOrderReturnDetail(String.valueOf(map.get("orderId")));
        if (returnOrderDetail != null) {
            Integer methodStatus = returnOrderDetail.getReturnMethodStatus();
            if (methodStatus == 2) {
                result.setData(CommonType.afterSalesMethods.ONLY_REFUND.getCode());
                result.setMessage(CommonType.afterSalesMethods.ONLY_REFUND.getDesc());
            } else if (methodStatus == 3) {
                result.setData(CommonType.afterSalesMethods.REFUND.getCode());
                result.setMessage(CommonType.afterSalesMethods.REFUND.getDesc());
            } else if (methodStatus == 1) {
                result.setData(CommonType.afterSalesMethods.RETURN.getCode());
                result.setMessage(CommonType.afterSalesMethods.RETURN.getDesc());
            }
        }else{
            result.setData(CommonType.afterSalesMethods.NO_AFTER_SALES.getCode());
            result.setMessage(CommonType.afterSalesMethods.NO_AFTER_SALES.getDesc());
        }
        result.setCode(CommonStatusEnum.SUCCESS.getCode());
        return result;
    }

    /**
     * @Description: 买家取消平台介入
     * @Param: [map]
     * @Return: com.yf.ShoppingCart.web.entity.ResultResp
     */
    @Override
    public ResponseResult revokePlatformIntervention(Map<String, Object> map) {
        ResponseResult resultResp = new ResponseResult();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
        }
        Map<String, Object> orderGoodsMap = new HashMap<>();
        String orderId = String.valueOf(map.get("orderId"));
        //查询平台介入
        OrderReturnPlatformVO orderReturnPlatform1 = orderReturnPlatformMapper.selectOrderReturnPlatform(orderId);

        ReturnOrderDetailVO returnOrderDetail = this.baseMapper.queryOrderReturnDetail(orderId);
        Integer methodStatus = returnOrderDetail.getReturnMethodStatus();

        OrderReturnPlatformVO orderReturnPlatform = new OrderReturnPlatformVO();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        Date Application_time = calendar.getTime();
        calendar.add(Calendar.DATE, 1);
        Date calendarTime = calendar.getTime();
        orderReturnPlatform.setOrderId(orderId);

        // 买家撤销
        orderGoodsMap.put("returnCode", map.get("returnCode"));
        orderGoodsMap.put("historicalReturnStatus", orderReturnPlatform1.getReturnState());

        orderGoodsMap.put("returnShopHandle", 0);
        if (methodStatus == 1 || methodStatus == 2) {
            orderGoodsMap.put("returnState", 15);
        } else if (methodStatus == 3) {
            orderGoodsMap.put("returnState", 16);
        }

        orderGoodsMap.put("closeTime", new Date());


        Map<String, Object> updateMap = new HashMap<>();
        Map<String, Object> updateGoodsMap = new HashMap<>();
        Integer torfOne = null;
        Integer torfTwo = null;
        updateMap.put("orderId", orderId);
        updateMap.put("orderRefundStatus", "0");// 原值：2，现改为0，用户可持续申请
        updateMap.put("orderReturnStatus", "0");// 原值：2，现改为0，用户可持续申请

        updateGoodsMap.put("orderId", orderId);

        updateGoodsMap.put("goodsReturnStatus", 0);
        updateGoodsMap.put("goodsRefundStatus", 0);
        //添加商家拒绝退款时间
        String businessTime = String.valueOf(System.currentTimeMillis());
        String businessRefundTime = DateUtils.stampToDate(businessTime);

        //更新平台介入状态
        orderReturnPlatformMapper.update(null, new LambdaUpdateWrapper<OrderReturnPlatformEntity>()
                .set(OrderReturnPlatformEntity::getInterventionState, CommonType.interventionState.BUYER_WITHDRAWAL.getCode())
                .set(OrderReturnPlatformEntity::getProcessingResults, CommonType.processingResults.USER_REVOCATION.getCode())
                .set(OrderReturnPlatformEntity::getProcessingTime, new Date())
                .eq(OrderReturnPlatformEntity::getOrderId, orderId));

        torfOne = orderBaseMapper.updateOrderBaseById(updateMap);
        //torfTwo = returnMoneyDao.updateOrderGoodsById(updateGoodsMap);

        //更新record表状态
        Map<String, String> feignMap = new HashMap<>();
        feignMap.put("orderId", orderId);
        feignMap.put("recordStatus", "7");// 原值：7
        payMentServiceClient.updateRefuse(feignMap);

        //if (1 != torfOne ||  torfTwo<1) {
        if (1 != torfOne) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            resultResp.setCode(2);
            return resultResp;
        }
        Integer torf = this.baseMapper.updateOrderReturnById(orderGoodsMap);
        if (torf > 0) {
            resultResp.setCode(1);
        }
        return resultResp;
    }

    @Override
    public ResponseResult calculatePrice(ApplyReturnOrderDTO applyReturnOrders) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(applyReturnOrders.getToken());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
        }
        if (StringUtils.isEmpty(applyReturnOrders.getOrderId())) {
            return ResponseResult.fail(2, "订单id不能为空");
        }
        OrderBaseVO orderBase = orderBaseMapper.getOrderBaseById(applyReturnOrders.getOrderId());
        BigDecimal discount=orderBase.getOrderPaymentAmount().divide(orderBase.getOrderGoodsAmount(),2, RoundingMode.HALF_UP);

        // 如果订单售后时间小于当前时间订单不可退
        if (orderBase.getVirtualGoods() != 0 && null != orderBase.getOrderLastReturnTime()
                && DateUtils.compareDate(orderBase.getOrderLastReturnTime(), DateUtils.getNowDate())) {
            return ResponseResult.fail(BizCodeEnume.GOODS_BEYOND_THE_AFTER_SALES_PERIOD);
        }
        String orderId = applyReturnOrders.getOrderId();

        Integer shopId = orderBase.getShopId();
        Integer orderGoodsNum = 0;
        // 根据商品己算退货价格
        List<ApplyReturnGoodDTO> applyReturnGoods = applyReturnOrders.getApplyReturnGoods();

        //判断当前订单是否全部退货
        Boolean huoBaoreturn = true;
        Double returnCash = 0.00;
        // 退货时商品总价格
        Double goodsAmount = 0.00;
        //售后红包金额
        Double returnRptCash = 0.00;
        //退还运费
        Double returnShippingFee = 0.00;
        //运费
        Double shippingFee = 0.00;
        //供应商 退还的 经销等级折扣
        BigDecimal orderDiscountFee = new BigDecimal(0);
        //查询运费
        List<Double> fees = orderGoodsMapper.selectList(new LambdaQueryWrapper<OrderGoodsEntity>()
                .eq(OrderGoodsEntity::getOrderId, orderId))
                .stream().map(OrderGoodsEntity::getShippingFee).collect(Collectors.toList());
        // 售后商品 + 售后促销 / 总商品 + 总促销（红包+代金券）
        for (ApplyReturnGoodDTO applyReturnGood : applyReturnGoods) {
            // 查询商品购买数量
            String orderGoodsId = applyReturnGood.getOrderGoodsId();

            ApplyReturnGoodDTO orderPurchaseQuantity = orderGoodsMapper.queryOrderPurchaseQuantity(orderId, orderGoodsId);
            if (orderPurchaseQuantity == null) {
                //应用退货为null，则进入下一次循环
                continue;
            }
            goodsAmount += Double.parseDouble(applyReturnGood.getOrderGoodsNum()) * Double.parseDouble(applyReturnGood.getOrderGoodsPrice());
            Map<String, String> getGoodsMap = new HashMap<>();
            getGoodsMap.put("orderId", applyReturnOrders.getOrderId());
            getGoodsMap.put("goodsId", applyReturnGood.getOrderGoodsId());
            OrderGoodsDiscountDTO orderGoodsDiscount = orderGoodsMapper.getGoodsDiscount(getGoodsMap);
            Integer orderGoodsNumTemp = 0;
            if (orderGoodsDiscount != null) {
                //商品价格加上售后促销价格
                goodsAmount += orderGoodsDiscount.getOrderRptPrice() + orderGoodsDiscount.getVoucherPrice();
                returnRptCash += orderGoodsDiscount.getOrderRptPrice();
                orderGoodsNumTemp = orderGoodsDiscount.getOrderGoodsNum().intValue();
            }
            Integer orderReturnGoodsNum = Integer.valueOf(applyReturnGood.getOrderGoodsNum());
            if (!orderGoodsNumTemp.equals(orderReturnGoodsNum)) {
                huoBaoreturn = false;
            }
            //计算运费
            if (null != orderPurchaseQuantity.getTotalGoodsShippingFee()) {
                shippingFee += orderPurchaseQuantity.getTotalGoodsShippingFee();
            }
//            shippingFee+=orderPurchaseQuantity.getShippingFee();

            // 判断：如果全部退则退还此商品实付，否则按比例退还
            if (applyReturnGood.getOrderGoodsNum().equals(orderPurchaseQuantity.getOrderGoodsNum())) {
                // 1.1 退回资金 = 应付金额（商品实际支付金额 + 运费- 促销）'(带运费)

                Double totalGoodsShippingFee = 0.0;
                if (null != orderPurchaseQuantity.getTotalGoodsShippingFee()) {
                    totalGoodsShippingFee = orderPurchaseQuantity.getTotalGoodsShippingFee();
                }
                returnCash += orderPurchaseQuantity.getOrderGoodsPaymentAmount() - orderPurchaseQuantity.getShippingFee() + totalGoodsShippingFee;
               // returnCash=new BigDecimal(returnCash).multiply(discount).doubleValue();
                //全部退 退经销等级折扣
                orderDiscountFee = orderBase.getDirectsellerDiscount();
            } else {
                if (null != orderBase.getOrderType() && 2 == orderBase.getOrderType()) {
                    // 退货金额 = ((实付金额-运费)/商品总金额)*退货商品价格*退货商品数量
                    returnCash += (orderBase.getOrderGoodsAmount().doubleValue() / Double.parseDouble(orderPurchaseQuantity.getOrderGoodsNum())) * Double.parseDouble(applyReturnGood.getOrderGoodsNum());
                } else {
                    // 退货金额 = ((实付金额-运费)/商品总金额)*退货商品价格*退货商品数量+(运费)
                    Double totalGoodsShippingFee = 0.0;
                    if (null != orderPurchaseQuantity.getTotalGoodsShippingFee()) {
                        totalGoodsShippingFee = orderPurchaseQuantity.getTotalGoodsShippingFee();
                    }
                    returnCash += ((orderPurchaseQuantity.getOrderGoodsPaymentAmount() - orderPurchaseQuantity.getShippingFee()) / Double.parseDouble(orderPurchaseQuantity.getOrderGoodsNum())) * Double.parseDouble(applyReturnGood.getOrderGoodsNum()) + totalGoodsShippingFee;
                }
                if (null != orderPurchaseQuantity.getOrderGoodsNum() && !"0".equals(orderPurchaseQuantity.getOrderGoodsNum())) {
                    orderDiscountFee = (orderBase.getDirectsellerDiscount().divide(new BigDecimal(orderPurchaseQuantity.getOrderGoodsNum()), 2, RoundingMode.HALF_UP)).multiply(new BigDecimal(applyReturnGood.getOrderGoodsNum()));
                }
            }
            //如果是 供应商代发货的订单 查询供应商的商品价格 计算退单金额
            //因为 同步是商品不能加购物车 所以 退货数量 和 退货商品价格是唯一  只会有一个商品
            if (null != orderBase.getDropShipping() && 1 == orderBase.getDropShipping()) {
                BigDecimal supperReturnPrice = new BigDecimal(0);
                supperReturnPrice = orderBase.getSupperGoodsPrice().multiply(new BigDecimal(applyReturnGood.getOrderGoodsNum()));
                //将退单的供应商 退款金额存入数据库
                orderSupplierBaseService.update(null, new LambdaUpdateWrapper<OrderSupplierBaseEntity>()
                        .set(OrderSupplierBaseEntity::getOrderReturnPrice, supperReturnPrice)
                        .eq(OrderSupplierBaseEntity::getOrderId, applyReturnOrders.getOrderId()));
            }
        }
        //如果huoBaoreturn 为true 证明当前订单 退货的商品数量与订单数量一致 （但也可能是一个订单里面的一个商品全部数量退货，另外的商品不退货，所以要判断是否是所有商品全部退货）
        if (!huoBaoreturn) {
            //判断订单是否是全部商品 全部退货
            Integer num = orderGoodsMapper.selectCount(new LambdaQueryWrapper<OrderGoodsEntity>()
                    .eq(OrderGoodsEntity::getOrderId, orderId));
            //如果是订单全部退货 就退红包（修改红包状态未使用，在商家退货确认收货接口修改），退红包 就在结算时写入红包金额
            if (num.equals(applyReturnGoods.size())) {
                //如果进来就证明该订单不是是全部退货就不退红包，不将红包金额写入结算  不退还 经销等级折扣
                returnRptCash = 0.00;
                returnShippingFee = 0.00;
            }
        }
        //退货金额
        BigDecimal tmp = new BigDecimal(returnCash);
        returnCash = tmp.setScale(2, RoundingMode.HALF_UP).doubleValue();
        Map map = new HashMap<>();
        map.put("returnCash", returnCash);
        map.put("shippingFee", shippingFee);
        map.put("orderShippingFee",orderBase.getOrderShippingFee());
        return ResponseResult.success(map);
    }

    @Override
    public ResponseResult listRefundOrder(Map<String, Object> paraMap) {
        IPage<ReturnOrderDetailVO> page = this.baseMapper.listRefundOrder(new Query<ReturnOrderDetailVO>().getPage(paraMap), paraMap);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult PlatformReturnDetail(Map<String, Object> paraMap) {
        ReturnOrderDetailVO returnDetail = this.baseMapper.refundDetail(paraMap);
        Map<String, String> selectMap = new HashMap<String, String>();
        selectMap.put("orderId", returnDetail.getOrderId());
        List<GoodsDetailsVO> listReturnGoods = this.baseMapper.listReturnGoods(selectMap);
        returnDetail.setGoodsDetails(listReturnGoods);
        if (returnDetail.getReturnShopHandle() == 3 && "5".equals(returnDetail.getReturnState())) {
            returnDetail.setReturnState("3");
        }
        return ResponseResult.success(returnDetail);
    }

    @Override
    public ResponseResult listRefundOrderExcel(Map<String, String> paraMap, HttpServletResponse response) {
        UserInfoVO info = ParseTokenUtils.getPlatformUser(paraMap.get("token"));
        if (null == info) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(), BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String finishTime = dateformat.format(new Date());
        List<ReturnOrderDetailVO> result = this.baseMapper.listrefundorderExp(paraMap);

        String[] headers = {"退单编号", "退单金额", "佣金金额", "申请原因", "申请时间", "商家处理备注", "商家处理时间", "订单编号",
                "买家", "商家", "付款时间", "退款状态"};
        List<Map<String, String>> listExcel = Lists.newArrayList();
        for (ReturnOrderDetailVO res : result) {
            HashMap<String, String> map = Maps.newHashMap();
            if (res.getReturnState() != null) {
                switch (res.getReturnState()) {
                    case "0":
                        res.setReturnState("卖家拒绝 ");
                        break;
                    case "1":
                        res.setReturnState("新发起等待卖家审核");
                        break;
                    case "2":
                        res.setReturnState("卖家审核通过  ");
                        break;
                    case "3":
                        res.setReturnState("卖家审核不通过 ");
                        break;
                    case "4":
                        res.setReturnState("卖家收到货物 ");
                        break;
                    case "5":
                        res.setReturnState("平台审核通过");
                        break;
                    case "6":
                        res.setReturnState("买家已填物流 ");
                        break;
                    case "7":
                        res.setReturnState("平台拒绝");
                        break;
                    case "8":
                        res.setReturnState("退款关闭");
                        break;
                    case "9":
                        res.setReturnState("平台介入中");
                        break;
                    case "15":
                        res.setReturnState("用户撤销退款关闭");
                        break;

                }
            }
            map.put("退单编号", res.getReturnCode());
            map.put("退单金额", res.getReturnCash().toString());
            map.put("佣金金额", res.getReturnCommisionFee());
            map.put("申请原因", res.getReturnReason());
            map.put("申请时间", res.getReturnAddTime());
            map.put("商家处理备注", res.getReturnShopMessage());
            map.put("商家处理时间", res.getReturnShopTime());
            map.put("订单编号", res.getOrderId());
            map.put("买家", res.getBuyerUserAccount());
            map.put("商家", res.getShopName());
            map.put("付款时间", res.getPaymentTime());
            map.put("退款状态", res.getReturnState());
            listExcel.add(map);
        }
        // excel文件名
        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         * 该list为每个sheet页的数据
         */> map = Maps
                .newHashMap();
        map.put("退款列表", listExcel);
        String url = ExcelsUtil.createExcel(headers, map, new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
        return ResponseResult.success(url);
    }

    @Override
    public ResponseResult queryOrderRemindDeliveryPort(OrderRemindDeliveryDTO param) {
        UserInfoVO info = ParseTokenUtils.getPlatformUser(param.getToken());
        if (info != null) {
            Map map = null;
            try {
                map = ParseMapUtils.beanToMap(param);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            IPage<OrderRemindDeliveryVO> page = this.baseMapper.queryOrderRemindDeliveryPort(new Query<OrderRemindDeliveryVO>().getPage(map), param);
            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(), BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    @Override
    public ResponseResult OrderRemindDeliveryPort(Map<String, String> param) {
        String orderSellerContact = param.get("orderSellerContact");
        String orderId = param.get("orderId");
        String orderReceiverName = param.get("buyerUserName");
        String timeDiff = param.get("timeDiff");
        if (orderSellerContact == null || orderSellerContact.equals("") ) {
            return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER.getCode(), "商家未配置手机号，不支持发送短信");
        } else {
            Map<String, String> map = new HashMap<>();
            map.put("orderSellerContact", orderSellerContact);
            map.put("orderReceiverName", orderReceiverName);
            map.put("timeDiff", timeDiff);
            map.put("orderId", orderId);
            thirdPartyServiceClient.pushTheDelivery(map);
        }
        return ResponseResult.success(BizCodeEnume.SENDING_SUCCEEDED.getMsg());
    }

    @Override
    public ResponseResult queryOrderRemindDeliveryPortExcel(OrderRemindDeliveryDTO param) {
        List<OrderRemindDeliveryVO> result = null;
        UserInfoVO info = ParseTokenUtils.getPlatformUser(param.getToken());
        if (info != null) {

            result = this.baseMapper.OrderRemindDeliveryPortExp(param);
            String[] headers = {"已付款时间(h)", "订单编号", "商品名称", "买家账号", "收件人姓名", "支付时间", "店铺名称", "店铺id", "店铺联系方式"};
            if (null != result && result.size() > 0) {
                List<Map<String, String>> list = Lists.newArrayList();
                for (OrderRemindDeliveryVO orderRemindDeliveryResult : result) {
                    HashMap<String, String> map = com.google.common.collect.Maps.newHashMap();
                    map.put("已付款时间(h)", String.valueOf(orderRemindDeliveryResult.getTimeDiff()));
                    if (StringUtils.isEmpty(orderRemindDeliveryResult.getOrderId())) {
                        map.put("订单编号", "无");
                    } else {
                        map.put("订单编号", orderRemindDeliveryResult.getOrderId());
                    }
                    if (StringUtils.isEmpty(orderRemindDeliveryResult.getGoodsName())) {
                        map.put("商品名称", "无");
                    } else {
                        map.put("商品名称", orderRemindDeliveryResult.getGoodsName());
                    }
                    if (StringUtils.isEmpty(orderRemindDeliveryResult.getBuyerUserName())) {
                        map.put("买家账号", "无");
                    } else {
                        map.put("买家账号", orderRemindDeliveryResult.getBuyerUserName());
                    }
                    if (StringUtils.isEmpty(orderRemindDeliveryResult.getOrderReceiverName())) {
                        map.put("收件人姓名", "无");
                    } else {
                        map.put("收件人姓名", orderRemindDeliveryResult.getOrderReceiverName());
                    }
                    if (StringUtils.isEmpty(orderRemindDeliveryResult.getPaymentTime())) {
                        map.put("支付时间", "无");
                    } else {
                        map.put("支付时间", orderRemindDeliveryResult.getPaymentTime());
                    }
                    if (StringUtils.isEmpty(orderRemindDeliveryResult.getShopName())) {
                        map.put("店铺名称", "无");
                    } else {
                        map.put("店铺名称", orderRemindDeliveryResult.getShopName());
                    }
                    if (StringUtils.isEmpty(orderRemindDeliveryResult.getShopId())) {
                        map.put("店铺id", "无");
                    } else {
                        map.put("店铺id", orderRemindDeliveryResult.getShopId());
                    }
                    if (StringUtils.isEmpty(orderRemindDeliveryResult.getOrderSellerContact())) {
                        map.put("店铺联系方式", "无");
                    } else {
                        map.put("店铺联系方式", orderRemindDeliveryResult.getOrderSellerContact());
                    }
                    list.add(map);
                }
                // excel文件名
                Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
                 * 该list为每个sheet页的数据
                 */> map = Maps
                        .newHashMap();
                map.put("提醒发货列表", list);
                String url = ExcelsUtil.createExcel(headers, map, new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
                return ResponseResult.success(url);
            } else {
                return ResponseResult.success(BizCodeEnume.SELECT_DATA_NULL.getCode(), BizCodeEnume.SELECT_DATA_NULL.getMsg());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(), BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    @Override
    public ResponseResult listReturnOrder(Map<String, Object> paraMap) {
        IPage<ReturnOrderDetailVO> page = this.baseMapper.listReturnRefund(new Query<ReturnOrderDetailVO>().getPage(paraMap), paraMap);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult listrefundorderExcel(Map<String, String> paraMap, HttpServletResponse response) {
        UserInfoVO info = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));
        if (null == info) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(), BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        List<ReturnOrderDetailVO> result = this.baseMapper.listReturnRefundExcel(paraMap);
        String[] headers = new String[]{"退单编号", "退单金额", "佣金金额", "申请原因", "申请时间", "商家处理备注", "商家处理时间", "订单编号", "卖家",
                "商家", "付款时间", "退货状态"};
        if (result != null && result.size() > 0) {
            List<Map<String, String>> list = Lists.newArrayList();
            for (ReturnOrderDetailVO res : result) {
                HashMap<String, String> map = Maps.newHashMap();
                if (res.getReturnState() != null) {
                    switch (res.getReturnState()) {
                        case "0":
                            res.setReturnState("卖家拒绝 ");
                            break;
                        case "1":
                            res.setReturnState("新发起等待卖家审核");
                            break;
                        case "2":
                            res.setReturnState("卖家审核通过  ");
                            break;
                        case "3":
                            res.setReturnState("卖家审核不通过 ");
                            break;
                        case "4":
                            res.setReturnState("卖家收到货物 ");
                            break;
                        case "5":
                            res.setReturnState("平台审核通过");
                            break;
                        case "6":
                            res.setReturnState("买家已填物流 ");
                            break;
                        case "7":
                            res.setReturnState("平台拒绝");
                            break;

                    }
                }
                map.put("退单编号", res.getReturnCode());
                map.put("退单金额", res.getReturnCash().toString());
                map.put("佣金金额", res.getReturnCommisionFee());
                map.put("申请原因", res.getReturnReason());
                map.put("申请时间", res.getReturnAddTime());
                map.put("商家处理备注", res.getReturnShopMessage());
                map.put("商家处理时间", res.getReturnShopTime());
                map.put("订单编号", res.getOrderId());
                map.put("买家", res.getBuyerUserAccount());
                map.put("商家", res.getShopName());
                map.put("付款时间", res.getPaymentTime());
                map.put("退款状态", res.getReturnState());
                list.add(map);
            }
            // excel文件名
            Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
             * 该list为每个sheet页的数据
             */> map = Maps
                    .newHashMap();
            map.put("测试合并数据", list);
            String url = ExcelsUtil.createExcel(headers, map, new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
            return ResponseResult.success(url);
        } else {
            return ResponseResult.success(BizCodeEnume.SELECT_DATA_NULL.getCode(), BizCodeEnume.SELECT_DATA_NULL.getMsg());
        }
    }

    @Override
    public ResponseResult queryReturnsaleReport(ReturnReportQueryDTO param) throws IllegalAccessException {
        if (null == param) {
            param = new ReturnReportQueryDTO();
        }

        Map data = ParseMapUtils.beanToMap(param);
        IPage<ReturnReportQueryseleVO> page = this.baseMapper.queryReturnsaleReport(new Query<ReturnReportQueryseleVO>().getPage(data),
                param);
        for (ReturnReportQueryseleVO res : page.getRecords()) {

            List<GoodsDetailsVO> parm = this.baseMapper.queryGoodsDetail(res.getOrderNumber());
            res.setGoods(parm);
        }

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryReturnsaleReportExcel(ReturnReportQueryDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            String[] title = {"订单号", "退款金额", "退货编号", "店铺名称", "买家名称", "买家账号", "支付单号", "第三方支付平台交易号", "应付金额", "支付方式", "退款状态",
                    "退款类型", "添加时间", "商家处理时间", "退款完成时间", "商品名称", "商品价格", "商品数量", "退货数量", "物流单号", "第三方支付金额", "充值卡余额支付"};
            List<Map<String, String>> list = Lists.newArrayList();
            //分页查询数据
            List<ReturnsaleReportVO> returnReportQueryseleResults = this.baseMapper.queryReturnsaleReportExcel(param);
            if (returnReportQueryseleResults.size() > 10000) {
                //导出数量过大，请联系运维
                return ResponseResult.fail(BizCodeEnume.EXPORT_QUANTITY_IS_TOO_LARGE);
            }
            for (ReturnsaleReportVO res : returnReportQueryseleResults) {
                // 订单状态 1.待付款 2.已付款 3.待发货 4.已发货 5.已签收 6.确认收货 7.取消 8.退款中 9.已退款 11.待自提',

                if (res.getPayCode() != null) {
                    switch (res.getPayCode()) {
                        // 0 无 1-余额支付，2-支付宝支付，3-微信支付，4-通联支付,5-健康账户余额支付',
                        case "0":
                            res.setPayCode("无");
                            break;
                        case "1":
                            res.setPayCode("余额支付");
                            break;
                        case "2":
                            res.setPayCode("支付宝支付");
                            break;
                        case "3":
                            res.setPayCode("微信支付");
                            break;
                        case "6":
                            res.setPayCode("充值卡支付");
                            break;
                        case "12":
                            res.setPayCode("线下支付");
                            break;
                        case "13":
                            res.setPayCode("账期支付");
                            break;
                        case "14":
                        case "15":
                            res.setPayCode("主管支付");
                            break;
                    }

                }
                if (res.getReturnType() != null) {
                    switch (res.getReturnType()) {
                        // 1-退款申请 2-退货申请 3-虚拟退款'
                        case "1":
                            res.setReturnType("退款申请");
                            break;
                        case "2":
                            res.setReturnType("退货申请 ");
                            break;
                        case "3":
                            res.setReturnType("虚拟退款");
                            break;
                    }
                }
                if (res.getReturnState() != null) {

                    switch (res.getReturnState()) {
                        case "1":
                            res.setReturnState("新发起等待卖家审核 ");
                            break;
                        case "2":
                            res.setReturnState("卖家审核通过 ");
                            break;
                        case "3":
                            res.setReturnState("卖家审核不通过");
                            break;
                        case "4":
                            res.setReturnState("卖家收到货物");
                            break;
                        case "5":
                            res.setReturnState("平台审核通过");
                            break;
                        case "6":
                            res.setReturnState("待卖家验收");
                            break;
                        case "8":
                            res.setReturnState("退款关闭");
                            break;
                        case "9":
                            res.setReturnState("平台介入中");
                            break;
                        case "13":
                            res.setReturnState(" 退货关闭");
                            break;
                        case "15":
                            res.setReturnState("用户撤销退款关闭");
                            break;
                        case "16":
                            res.setReturnState("用户撤销退货关闭");
                            break;
                    }
                }
                HashMap<String, String> map = Maps.newHashMap();
                map.put("订单号", res.getOrderId());
                map.put("退款金额", res.getReturnCash() + "");
                map.put("退货编号", res.getReturnCode());
                map.put("店铺名称", res.getShopName());
                map.put("买家名称", res.getBuyerUserName());
                map.put("买家账号", res.getBuyerUserAccount());
                map.put("支付单号", res.getPaymentNumber());
                map.put("第三方支付平台交易号", res.getPaymentOtherNumber() == null ? "" : res.getPaymentOtherNumber()+"");
                map.put("应付金额", res.getOrderPaymentAmount() + "");
                map.put("支付方式", res.getPayCode());
                map.put("退款状态", res.getReturnState());
                map.put("退款类型", res.getReturnType());
                map.put("添加时间", res.getReturnAddTime() + "");
                map.put("商家处理时间", res.getReturnShopTime() == null ? "" : res.getReturnShopTime()+"");
                map.put("退款完成时间", res.getReturnFinishTime() == null ? "" : res.getReturnFinishTime()+"");
                map.put("商品名称", res.getGoodsName());
                map.put("商品价格", res.getGoodsPrice());
                map.put("商品数量", res.getOrderGoodsNum() + "");
                map.put("退货数量", res.getOrderGoodsReturnnum() + "");
                map.put("物流单号", res.getOrderShippingCode());
                map.put("第三方支付金额", res.getTradeThirdPartyAmount() + "");
                map.put("充值卡余额支付", res.getTradePaymentRechargeCard() + "");
                list.add(map);
            }
            Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
             */> map = Maps.newHashMap();
            map.put("售后服务", list);
            String url = ExcelsUtil.createExcel(title, map, new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
            return ResponseResult.success(url);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult listRefund(Map<String, Object> map) {
        String token = map.get("token").toString();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (null == userInfo.getShopId()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        map.put("shopId", userInfo.getShopId());
        if (userInfo.getShopType() != null) {
            map.put("shopType", userInfo.getShopType().toString());
        }
        // 退款
        map.put("returnType", "1");

        Page<SellerOrderDetailVO> page = new Page<>((Integer) map.get("page"), (Integer) map.get("limit"));
        IPage<SellerOrderDetailVO> sellerOrderDetails = this.baseMapper.listRefund(page, map);
        if (null != sellerOrderDetails) {
            HashMap refundMap = new HashMap();
            for (SellerOrderDetailVO sellerOrderDetail : sellerOrderDetails.getRecords()) {
//                InquiryBaseDTO inquiryBase = this.baseMapper.getInquiryBase(sellerOrderDetail.getOrderId());
//                if (inquiryBase != null) {
//                    sellerOrderDetail.setInquiryId(inquiryBase.getInquiryId());
//                }
                String orderId = sellerOrderDetail.getOrderId();
                refundMap.put("orderId", orderId);
                List<GoodsDetailsListVO> listReturnGoods = this.baseMapper.listReturnGoods1(refundMap);
                sellerOrderDetail.setOrderGoodsDetail(listReturnGoods);
                refundMap.clear();

                //处理供应商代发商品
                if (sellerOrderDetail.getDropShipping() != null && sellerOrderDetail.getDropShipping() == 1 && userInfo.getShopType() == 2){
                    if (sellerOrderDetail.getSupperRefundPrice() != null){
                        sellerOrderDetail.setReturnCash(sellerOrderDetail.getSupperRefundPrice().doubleValue());
                    }
                    sellerOrderDetail.setOrderPaymentAmount(sellerOrderDetail.getSupperPaymentAmount().toString());
                }
            }
        }
        return ResponseResult.success(PageUtils.getPage(sellerOrderDetails));
    }

    @Override
    public ResponseResult forSellerApprove(Map<String, String> map) throws TransactionException {
        String token = map.get("token");
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (null == userInfo.getShopId()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        map.put("shopId", userInfo.getShopId());
        map.put("userId", userInfo.getUserId());
        map.put("shopType", String.valueOf(userInfo.getShopType()));
        map.put("orderOperator", userInfo.getUserName());
        Boolean torf = forSellerApproveBoolean(map);
        if (!torf) {
            return ResponseResult.fail(2, "审核失败");
        }
        return ResponseResult.success(1, "审核成功");
    }

    public Boolean forSellerApproveBoolean(Map<String, String> paraMap) throws TransactionException {
        Map<String, Object> orderGoodsMap = new HashMap<>();
        Map<String, Object> orderBaseMap = new HashMap<>();
        Map<String,Object> assetDetailMap = new HashMap<>();
        orderGoodsMap.put("orderOperator",paraMap.get("orderOperator"));
        OrderReturnEntity orderReturnEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<OrderReturnEntity>()
                .eq(OrderReturnEntity::getReturnCode, paraMap.get("returnCode")));
        String orderId = orderReturnEntity.getOrderId();
        OrderBaseEntity entity = orderBaseMapper.selectById(orderId);
        Integer orderStatus = this.baseMapper.queryOrderStatus(orderId);
        Integer virtualGoods = 1;
        //获取退货数量
        Map<String,Object> goodsNumMap = new HashMap<>();
        List<Map<String,Object>> goodsNum = this.baseMapper.queryBuyNumByorderId(orderId);
        goodsNumMap.put("goodsNum",goodsNum);
        String buyerUserId = goodsNum.get(0).get("buyer_user_id").toString();//买家id
        //判断是否是虚拟订单 且没有被核销
        Map<String, Object> map  = this.baseMapper.selectisVirtualOrderByTime(orderId);
        if(null  != map){
            virtualGoods = 0;
            //如果该虚拟订单已过期 且过期不退款直接返回false
            Integer result = this.baseMapper.queryisVirtualOrderByTime(orderId);
            if( 0 != result){
                return false;
            }
        }

        //查询用户售后商品
        List<Integer> returnGoods = this.baseMapper.queryReturnGoods(orderId);

        // 商家同意
        if (1 == Integer.parseInt(paraMap.get("type"))) {
            BigDecimal returnCash;
            if(orderStatus == 6){
                //用户收到货物退款
                orderGoodsMap.put("returnCode", paraMap.get("returnCode"));
                orderGoodsMap.put("returnShopHandle", 2);
                //4-卖家收到货物
                orderGoodsMap.put("returnState", 2);
                orderGoodsMap.put("returnShopMessage", paraMap.get("returnShopMessage"));
                orderGoodsMap.put("returnShopTime", new Date());
                orderGoodsMap.put("returnFinishTime",TimeStampUtil.getNowDate());

                //	 1.2修改商家同意订单状态为 6
                orderBaseMap.put("orderId",orderId);
                //9.已退款
                orderBaseMap.put("orderStatus","9");
                //2是退款完成
                orderBaseMap.put("orderRefundStatus","2");
                //2是退款完成
                orderBaseMap.put("orderReturnStatus","0");
                Integer torf = this.baseMapper.updateOrderBaseById(orderBaseMap);

                Map<String, Object> updateGoodsMap = new HashMap<>();
                updateGoodsMap.put("orderId",orderId);
                updateGoodsMap.put("goodsRefundStatus",2);
                updateGoodsMap.put("goodsReturnStatus",0);
                for (Integer returnGood : returnGoods) {
                    updateGoodsMap.put("goodsId",returnGood);
                    this.baseMapper.updateOrderGoodsById1(updateGoodsMap);
                }


                String uOrderId = this.baseMapper.queryPaymentNumber(orderId);
                returnCash = this.baseMapper.queryReturnCash(orderId);

                List<Integer> orderTradeStatus = this.baseMapper.queryOrderRecordStatus(uOrderId);
                RefundParamDTO refundPara = new RefundParamDTO();
                boolean isRefundSuccess = false;
                if(torf == 1) {
                    refundPara = this.baseMapper.queryRefundPara(orderId);
                    refundPara.setOrderTradeStatus(orderTradeStatus);
                    refundPara.setReturnCash(returnCash);
                    refundPara.setShopId(Integer.valueOf(paraMap.get("shopId")));
                    refundPara.setShopType(Integer.valueOf(paraMap.get("shopType")));
                    isRefundSuccess = waitShipmentsRefund(refundPara);
                    //退款更新商品销量
                    updateGoodsSalenum(goodsNumMap);
                }
                if(!isRefundSuccess){
                    // 回滚
                    GlobalTransactionContext.reload(RootContext.getXID()).rollback();
                    return false;
                }
                if (1 != torf ) {
                    // 回滚
                    GlobalTransactionContext.reload(RootContext.getXID()).rollback();
                    return false;
                }
                //退还红包优惠卷
                returnred(orderId,returnCash,returnGoods);

                //退还积分
                refundpoints(orderId,returnCash);
                //已发货退款  且是普通商品 不能是虚拟商品
            }else if(orderStatus == 4 && virtualGoods == 1){
                orderGoodsMap.put("returnCode", paraMap.get("returnCode"));
                orderGoodsMap.put("returnShopHandle", 2);
                orderGoodsMap.put("returnState", 2);
                orderGoodsMap.put("returnShopMessage", paraMap.get("returnShopMessage"));
                orderGoodsMap.put("returnShopTime", new Date());

                //	 1.2修改商家同意订单状态为 6
                orderBaseMap.put("orderId",orderId);
                orderBaseMap.put("orderStatus","9");
                orderBaseMap.put("orderRefundStatus","2");
                orderBaseMap.put("orderFinishedTime",TimeStampUtil.getNowDate());
                Integer torf = this.baseMapper.updateOrderBaseById(orderBaseMap);
                Map<String, Object> updateGoodsMap = new HashMap<>();
                updateGoodsMap.put("orderId",orderId);
                updateGoodsMap.put("goodsRefundStatus",2);
                this.baseMapper.updateOrderGoodsById(updateGoodsMap);

                String uOrderId = this.baseMapper.queryPaymentNumber(orderId);
                returnCash = this.baseMapper.queryReturnCash(orderId);
                List<Integer> orderTradeStatus = this.baseMapper.queryOrderRecordStatus(uOrderId);
                RefundParamDTO refundPara = new RefundParamDTO();
                boolean isRefundSuccess = false;
                if(torf == 1) {
                    refundPara = this.baseMapper.queryRefundPara(orderId);
                    refundPara.setOrderTradeStatus(orderTradeStatus);
                    refundPara.setReturnCash(returnCash);
                    refundPara.setShopId(Integer.valueOf(paraMap.get("shopId")));
                    refundPara.setShopType(Integer.valueOf(paraMap.get("shopType")));
                    isRefundSuccess = waitShipmentsRefund(refundPara);
                    updateGoodsSalenum(goodsNumMap);//退款更新商品销量
                }
                if(!isRefundSuccess){
                    // 回滚
                    GlobalTransactionContext.reload(RootContext.getXID()).rollback();
                    return false;
                }

                if (1 != torf ) {
                    // 回滚
                    GlobalTransactionContext.reload(RootContext.getXID()).rollback();
                    return false;
                }
            }else if(orderStatus == 3 || virtualGoods == 0){
                //未发货退款  虚拟商品订单可以进来
                orderGoodsMap.put("returnCode", paraMap.get("returnCode"));
                orderGoodsMap.put("returnShopHandle", 2);
                //卖家审核通过
                orderGoodsMap.put("returnState", 2);
                orderGoodsMap.put("returnShopMessage", paraMap.get("returnShopMessage"));
                orderGoodsMap.put("returnShopTime", new Date());
                orderGoodsMap.put("returnFinishTime",TimeStampUtil.getNowDate());

                //	 1.2修改商家同意订单状态为 6
                orderBaseMap.put("orderId",orderId);
                //已退款
                orderBaseMap.put("orderStatus","9");
                orderBaseMap.put("orderRefundStatus","2");
                orderBaseMap.put("orderReturnStatus","0");
                orderBaseMap.put("orderFinishedTime",TimeStampUtil.getNowDate());
                Integer torf = this.baseMapper.updateOrderBaseById(orderBaseMap);
                Map<String, Object> updateGoodsMap = new HashMap<>();
                updateGoodsMap.put("orderId",orderId);
                updateGoodsMap.put("goodsRefundStatus", 2);
                updateGoodsMap.put("goodsReturnStatus", 0);
                this.baseMapper.updateOrderGoodsById(updateGoodsMap);

                String uOrderId = this.baseMapper.queryPaymentNumber(orderId);
                returnCash = this.baseMapper.queryReturnCash(orderId);

                List<Integer> orderTradeStatus = this.baseMapper.queryOrderRecordStatus(uOrderId);
                RefundParamDTO refundPara = new RefundParamDTO();
                boolean isRefundSuccess = false;
                if(torf == 1) {
                    refundPara = this.baseMapper.queryRefundPara(orderId);
                    refundPara.setOrderTradeStatus(orderTradeStatus);
                    refundPara.setReturnCash(returnCash);
                    refundPara.setShopId(Integer.valueOf(paraMap.get("shopId")));
                    refundPara.setShopType(Integer.valueOf(paraMap.get("shopType")));
                    System.out.println("+++++++" + refundPara);
                    updateGoodsSalenum(goodsNumMap);
                    if (refundPara.getPayCode() != 12) {
                        isRefundSuccess = waitShipmentsRefund(refundPara);
                    } else {
                        isRefundSuccess = true;
                    }
                }
                if(!isRefundSuccess){
                    // 回滚
                    GlobalTransactionContext.reload(RootContext.getXID()).rollback();
                    return false;
                }
                if (1 != torf ) {
                    // 回滚
                    GlobalTransactionContext.reload(RootContext.getXID()).rollback();
                    return false;
                }
                //退款成功后 修改库存
                //获取goodsid commonid 购买数量
                List<WapGoodsSaleSumUpdateVO> wapGood = this.baseMapper.queryGoodsXinXi(orderId);
                for (WapGoodsSaleSumUpdateVO wapGoodsSaleSumUpdate : wapGood) {
                    this.baseMapper.updateCommonStockByGoodsId(wapGoodsSaleSumUpdate);
                    this.baseMapper.updateGoodsStockByGoodsId(wapGoodsSaleSumUpdate);

                    //遍历集合减去销量
                    this.baseMapper.lessgoodsBySales(wapGoodsSaleSumUpdate);
                }

                //退还红包和代金卷
                returnred(orderId,returnCash,returnGoods);
            }else{
                return false;
            }
            // 售后分销佣金处理
            commissionReturn(orderId,returnCash);

            // 代发货订单 经销商和供应商佣金处理
            BigDecimal totalDealerCommission = BigDecimal.ZERO;
            BigDecimal totalSupplyCommission = BigDecimal.ZERO;
            List<OrderSupplyCommissionDTO> supplyCommissionList = this.baseMapper.queryOrderSupplyCommission(orderId);
            for(OrderSupplyCommissionDTO orderSupplyCommission : supplyCommissionList) {
                if (null != orderSupplyCommission && returnCash != null && !returnCash.equals(new BigDecimal("0.00"))) {
                    // 退还的经销商和分销商佣金
                    BigDecimal returnDealerCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(), 2,
                            RoundingMode.HALF_UP).multiply(orderSupplyCommission.getDealerCommission()).setScale(2, RoundingMode.HALF_UP);
                    BigDecimal returnSupplCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(), 2,
                            RoundingMode.HALF_UP).multiply(orderSupplyCommission.getSupplyCommission()).setScale(2, RoundingMode.HALF_UP);
                    orderSupplyCommission.setDealerReturnCommission(returnDealerCommission);
                    orderSupplyCommission.setSupplyReturnCommission(returnSupplCommission);
                    // 订单总的退还佣金
                    totalDealerCommission = totalDealerCommission.add(returnDealerCommission);
                    totalSupplyCommission = totalSupplyCommission.add(totalSupplyCommission);
                }
            }
            // 由于退款 是全订单退款 所以退红包
            this.baseMapper.updateHongbaoStart(orderId);
            //更新商品订单退还佣金
            this.baseMapper.updateOrderGoodsCommissionBatch(supplyCommissionList);
            // 更新订单退还佣金
            this.baseMapper.updateOrderSupplyCommission(orderId,totalDealerCommission,totalSupplyCommission);

            //插入我的余额明细表
            assetDetailMap.put("orderId",orderId);
            assetDetailMap.put("detailType",2);
            assetDetailMap.put("assetType",1);
            assetDetailMap.put("assetAmount",returnCash);
            AssetDirectionAndPayTypeInfoDTO assetInfo = this.baseMapper.getAssetDirectionAndPayTypeInfo(orderId);
            if(null != assetInfo){
                assetDetailMap.put("assetDirection",assetInfo.getAssetDirection());
                assetDetailMap.put("payType",assetInfo.getPayType());
                assetDetailMap.put("userId",assetInfo.getUserId());
                this.baseMapper.insertDetail(assetDetailMap);
            }//判断是否是虚拟订单 且没有被核销
            if(null  != map){
                virtualGoods = 0;
                //是否核销 0是 1否 2已过期
                Integer isCancel = Integer.parseInt(map.get("isCancel").toString());
                if(null != isCancel && 0 != isCancel) {
                    //如果该虚拟订单已过期 且过期不退款直接返回false
                    Integer result = this.baseMapper.queryisVirtualOrderByTime(orderId);
                    if (0 != result) {
                        return false;
                    }
                    boolean returnFlag = false;
                    //未核销且在有效期内
                    if( 1 == isCancel){
                        Integer result1 = this.baseMapper.queryisVirtualOrderByTime1(orderId);
                        if(null != result1 && result1 >0){
                            returnFlag = true;
                        }
                        //过期且可过期退款
                    }else if( 2 == isCancel){
                        Integer result2 = this.baseMapper.queryisVirtualOrderByTime2(orderId);
                        if(null != result2 && result2 >0){
                            returnFlag = true;
                            //退还虚拟订单佣金
                            //如果该虚拟订单已过期 且过期允许退款就扣除积分
                            //扣减积分
                            //修改会员积分和会员等级
                            //根据orderid 查询应该回退的积分和userid
                            Map<String, Object> tmpMap = this.baseMapper.queryAddpointsLogByOrderId(orderId);
                            if (null != tmpMap) {
                                MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
                                ArrayList<String> list = new ArrayList<>();
                                list.add((String) tmpMap.get("user_id"));
                                updateMemberMessageListIntegral.setUserIdList(list);
                                updateMemberMessageListIntegral.setIntegral((Integer) tmpMap.get("points_log_points"));
                                updateMemberMessageListIntegral.setType(0);//1是增加积分 0 是扣除积分
                                feignUpdateMemberIntegral(updateMemberMessageListIntegral);
                                //添加积分修改记录
                                UserPointLogParamDTO userPointLog = new UserPointLogParamDTO();
                                userPointLog.setPointsLogType(2);
                                userPointLog.setClassId(9);
                                userPointLog.setPointsLogTime(new Date());
                                userPointLog.setPointsLogDesc("商品退款");
                                userPointLog.setPointsLogFlag("reg");
                                userPointLog.setUserId(tmpMap.get("user_id").toString());
                                userPointLog.setPointsLogPoints((Integer) tmpMap.get("points_log_points"));
                                userPointLog.setPointsLogOperate("商品退款");
                                userPointLog.setOrderId(paraMap.get("orderId"));
                                this.baseMapper.feginAddpointsLog(userPointLog);
                            }

                        }
                    }
                    if(returnFlag){
                        Map<String, Object> dataMap = this.baseMapper.queryOrderReturnInfoById(orderId);
                        dataMap.put("orderId",orderId);
                        if (returnCash != null && entity.getOrderPaymentAmount().compareTo(returnCash) > 0) {
                            BigDecimal lv = orderReturnEntity.getReturnCash().divide(entity.getOrderPaymentAmount(), 2, RoundingMode.HALF_UP);
                            if(entity.getOrderCommissionFee() != null) {
                                dataMap.put("orderCommissionFee", BigDecimal.valueOf(entity.getOrderCommissionFee()).multiply(lv).setScale(2, RoundingMode.HALF_UP));
                            }
                            if(entity.getBaseMemberDiscount() != null) {
                                dataMap.put("baseMemberDiscount", BigDecimal.valueOf(entity.getBaseMemberDiscount()).multiply(lv).setScale(2, RoundingMode.HALF_UP));
                            }
                            if(entity.getDistributionDiscount() != null) {
                                dataMap.put("distributionDiscount", entity.getDistributionDiscount().multiply(lv).setScale(2, RoundingMode.HALF_UP));
                            }
                        }
                        this.baseMapper.updateOrderReturnInfoById(dataMap);
                    }
                }
            }
            //普通订单,退回积分
            if (virtualGoods == 1) {
                Map<String, Object> dataMap = this.baseMapper.queryOrderReturnInfoById(orderId);
                if (returnCash != null && entity.getOrderPaymentAmount().compareTo(returnCash) > 0) {
                    BigDecimal lv = orderReturnEntity.getReturnCash().divide(entity.getOrderPaymentAmount(), 2, RoundingMode.HALF_UP);
                    if(entity.getOrderCommissionFee() != null) {
                        dataMap.put("orderCommissionFee", BigDecimal.valueOf(entity.getOrderCommissionFee()).multiply(lv).setScale(2, RoundingMode.HALF_UP));
                    }
                    if(entity.getBaseMemberDiscount() != null) {
                        dataMap.put("baseMemberDiscount", BigDecimal.valueOf(entity.getBaseMemberDiscount()).multiply(lv).setScale(2, RoundingMode.HALF_UP));
                    }
                    if(entity.getDistributionDiscount() != null) {
                        dataMap.put("distributionDiscount", entity.getDistributionDiscount().multiply(lv).setScale(2, RoundingMode.HALF_UP));
                    }
                }
                dataMap.put("orderId", orderId);
                this.baseMapper.updateOrderReturnInfoById(dataMap);
            }
            //退款完成时间
            orderGoodsMap.put("returnFinishTime", LocalDateTime.now());
            //罚扣质保金
            charging(orderId,returnGoods, paraMap.get("userId"),Integer.valueOf(paraMap.get("shopId")));

            //退回plus折扣额度
            try {
                orderBaseService.plusdis(orderId,buyerUserId,returnGoods);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            // 商家不同意
            orderGoodsMap.put("returnCode", paraMap.get("returnCode"));
            orderGoodsMap.put("returnShopHandle", 0);
            orderGoodsMap.put("returnState", 3);
            orderGoodsMap.put("returnShopMessage", paraMap.get("returnShopMessage"));
            orderGoodsMap.put("returnShopTime", new Date());
            Calendar instance = Calendar.getInstance();
            instance.setTime(new Date());
            instance.add(Calendar.DATE,2);
            Date expiration_time = instance.getTime();
            orderGoodsMap.put("expirationTime", expiration_time);

            Map<String, Object> updateMap = new HashMap<String, Object>();
            Map<String, Object> updateGoodsMap = new HashMap<String, Object>();
            Integer torfOne = null;
            Integer torfTwo = null;
            updateMap.put("orderId", orderId);
            // 原值：2，现改为0，用户可持续申请
            updateMap.put("orderRefundStatus", "3");
            // 原值：2，现改为0，用户可持续申请
            updateMap.put("orderReturnStatus", "0");

            updateGoodsMap.put("orderId",orderId);

            updateGoodsMap.put("goodsReturnStatus",0);
            updateGoodsMap.put("goodsRefundStatus",3);
            for (Integer returnGood : returnGoods) {
                updateGoodsMap.put("goodsId",returnGood);
                torfTwo = this.baseMapper.updateOrderGoodsById1(updateGoodsMap);
            }

            //添加商家拒绝退款时间
            String businessTime =String.valueOf(System.currentTimeMillis());
            String businessRefundTime=TimeStampUtil.stampToDate(businessTime);

            updateGoodsMap.put("businessRefundTime",businessRefundTime);

            torfOne = this.baseMapper.updateOrderBaseById(updateMap);

            //更新record表状态
            Map<String,String> feignMap = new HashMap<>();
            feignMap.put("orderId",orderId);
            // 原值：7
            feignMap.put("recordStatus","8");
            this.baseMapper.updateRefuse(feignMap);

            if (1 != torfOne ||  torfTwo<1) {
                GlobalTransactionContext.reload(RootContext.getXID()).rollback();
                return false;
            }
        }
        Integer torf = this.baseMapper.updateOrderReturnById(orderGoodsMap);
        if (1 == torf) {
            return true;
        }
        return false;
    }

    @Override
    public ResponseResult returnorder(Map<String, Object> paraMap) {
        String token = paraMap.get("token").toString();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (null == userInfo.getShopId()) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        paraMap.put("shopId", userInfo.getShopId());
        paraMap.put("returnType", "2");
        if (userInfo.getShopType() != null) {
            paraMap.put("shopType", userInfo.getShopType().toString());
        }

        Page<ReturnOrderVO> page = new Page<>((Integer) paraMap.get("page"), (Integer) paraMap.get("limit"));
        IPage<ReturnOrderVO> returnRefundList = this.baseMapper.listReturnOrders(page, paraMap);
        for (ReturnOrderVO returnOrder : returnRefundList.getRecords()) {
            // 退货，可能又多件商品
            Map<String, String> selectMap = new HashMap<String, String>();
            List<GoodsDetailsVO> goodsDetails = new ArrayList<GoodsDetailsVO>();
            selectMap.put("orderId", returnOrder.getOrderId());
            goodsDetails = this.baseMapper.listReturnGoods(selectMap);
            returnOrder.setGoodsDetails(goodsDetails);
            //InquiryBaseDTO inquiryBase = this.baseMapper.getInquiryBase(returnOrder.getOrderId());
//            if (inquiryBase != null) {
//                returnOrder.setInquiryId(inquiryBase.getInquiryId());
//            }

            //判断是否是代发货订单
            if (null != returnOrder.getDropShipping() && 1 == returnOrder.getDropShipping() && userInfo.getShopType() == 2) {
                if (returnOrder.getSupperReturnPrice() != null){
                    returnOrder.setReturnCash(returnOrder.getSupperReturnPrice().toString());
                }
               returnOrder.setOrderPaymentAmount(returnOrder.getSupperPaymentAmount().toString());
            }
        }
        return ResponseResult.success(PageUtils.getPage(returnRefundList));
    }

    @Override
    public ResponseResult retForSellerApprove(Map<String, Object> map) {
        String token = map.get("token").toString();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (null == userInfo.getShopId()) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        map.put("userInfo", userInfo);
        Boolean torf = retForSellerApproveBoolean(map);
        if (!torf) {
            return ResponseResult.fail(2, "审核失败");
        }
        return ResponseResult.success(1, "审核成功");

    }

    @Transactional
    public Boolean retForSellerApproveBoolean(Map<String, Object> paraMap) {
        Map<String, Object> orderGoodsMap = new HashMap<>();
        UserInfoVO userInfo = (UserInfoVO) paraMap.get("userInfo");
            orderGoodsMap.put("orderOperator",userInfo.getUserName());
        ManageShopAddressQueryVO returnAddr = null;
        String orderId = this.baseMapper.getOrderIdByReturnCode(paraMap.get("returnCode").toString());
        BigDecimal returnCash = this.baseMapper.queryReturnCash(orderId);
        if (paraMap.get("returnAddrId") != null && paraMap.get("returnAddrId") != ""){
            returnAddr = queryReturnShop(Integer.valueOf(paraMap.get("returnAddrId").toString()),paraMap.get("token").toString());
        }
        // 商家同意
        if (1 == Integer.parseInt(paraMap.get("type").toString())) {
            orderGoodsMap.put("returnCode", paraMap.get("returnCode"));
            orderGoodsMap.put("returnShopHandle", 2);
            orderGoodsMap.put("returnState", 2);
            orderGoodsMap.put("returnAddrId", paraMap.get("returnAddrId"));
            orderGoodsMap.put("returnAddr", paraMap.get("returnAddr"));
            orderGoodsMap.put("returnAddrName", paraMap.get("returnAddr"));
            orderGoodsMap.put("returnShopMessage", paraMap.get("returnShopMessage"));
            orderGoodsMap.put("returnShopTime", new Date());
            Calendar instance = Calendar.getInstance();
            instance.setTime(new Date());
            instance.add(Calendar.DATE,7);
            Date expirationTime = instance.getTime();
            if (returnAddr != null){
                orderGoodsMap.put("returnRealName", returnAddr.getShippingAddressContact());
                orderGoodsMap.put("returnNumber", returnAddr.getShippingAddressPhone());
            }
            orderGoodsMap.put("expirationTime", expirationTime);
        } else {
            // 商家不同意
            orderGoodsMap.put("returnCode", paraMap.get("returnCode"));
            orderGoodsMap.put("returnShopHandle", 3);
            orderGoodsMap.put("returnState", 3);
            orderGoodsMap.put("returnShopMessage", paraMap.get("returnShopMessage"));
            orderGoodsMap.put("returnAddrId", paraMap.get("returnAddrId"));
            orderGoodsMap.put("returnAddr", paraMap.get("returnAddr"));
            orderGoodsMap.put("returnAddrName", paraMap.get("returnAddr"));
            orderGoodsMap.put("returnShopTime", new Date());
            orderGoodsMap.put("orderId", orderId);
            Calendar instance = Calendar.getInstance();
            instance.setTime(new Date());
            instance.add(Calendar.DATE,2);
            Date expirationTime = instance.getTime();
            if (returnAddr != null){
                orderGoodsMap.put("returnRealName", returnAddr.getShippingAddressContact());
                orderGoodsMap.put("returnNumber", returnAddr .getShippingAddressPhone());
            }

            orderGoodsMap.put("expirationTime", expirationTime);
            this.baseMapper.updateOrderBaseById1(orderGoodsMap);

            Map<String, Object> updateMap = new HashMap<>();
            updateMap.put("orderId", orderId);
            updateMap.put("orderRefundStatus","0");
            updateMap.put("orderReturnStatus", "3");
            Integer torf = this.baseMapper.updateOrderBaseById(updateMap);
            if (1 != torf) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        }

        Integer torf = this.baseMapper.updateOrderReturnById(orderGoodsMap);
        if (1 == torf) {
            return true;
        }
        return false;
    }

    @Override
    public ResponseResult retForSellerReceive(Map<String, String> map) {
        String token = map.get("token");
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (null == userInfo.getShopId()) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        map.put("shopId", userInfo.getShopId());
        map.put("shopType", String.valueOf(userInfo.getShopType()));
        map.put("userId", String.valueOf(userInfo.getUserId()));
        Boolean torf = retForSellerReceiveBoolean(map);
        if (!torf) {
            return ResponseResult.fail(2, "审核失败");
        }
        return ResponseResult.success(1, "审核成功");
    }

    @Override
    public ResponseResult selectshopordereturn(Map<String, Object> map) {
        String orderId = String.valueOf(map.get("orderId"));
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //查询退款详情
        ReturnOrderDetailVO returnOrderDetail = this.baseMapper.queryOrderReturnDetail(orderId);
        if (returnOrderDetail != null){
            if (returnOrderDetail.getReturnVoucher() != null){
                String returnVoucher = returnOrderDetail.getReturnVoucher();
                List<String> imgs = JSONArray.parseArray(returnVoucher, String.class);
                returnOrderDetail.setReturnVouchers(imgs);
                returnOrderDetail.setReturnVoucher(null);
            }
        }
        //查询售后商品
        List<GoodsDetailsListVO> orderGoods = orderGoodsMapper.queryGoodsList1(orderId);
        returnOrderDetail.setOrderGoodsDetail(orderGoods);
        //查询平台介入
        OrderReturnPlatformVO orderReturnPlatform = orderReturnPlatformMapper.selectOrderReturnPlatform(orderId);

        if (orderReturnPlatform != null){
            String buyer_voucher = orderReturnPlatform.getBuyerVoucher();
            String seller_voucher = orderReturnPlatform.getSellerVoucher();
            if (seller_voucher != null){
                List<String> imgs = JSONArray.parseArray(seller_voucher, String.class);
                orderReturnPlatform.setSellerVouchers(imgs);
                orderReturnPlatform.setSellerVoucher(null);
            }
            if (buyer_voucher != null) {
                List<String> imgs = JSONArray.parseArray(buyer_voucher, String.class);
                orderReturnPlatform.setBuyerVouchers(imgs);
                orderReturnPlatform.setBuyerVoucher(null);
            }
            orderReturnPlatform.setReturnOrderDetail(returnOrderDetail);
            return ResponseResult.success(orderReturnPlatform);
        }
        if (orderGoods != null && orderGoods.size()>0){
            return ResponseResult.success(returnOrderDetail);
        }
        return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
    }

    @Override
    public ResponseResult insertShopIntervention(Map<String, Object> map) {
        String orderId = String.valueOf(map.get("orderId"));
        OrderReturnPlatformVO orderReturnPlatform = new OrderReturnPlatformVO();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        Date Application_time = calendar.getTime();
        calendar.add(Calendar.DATE,4);
        Date calendarTime = calendar.getTime();
        orderReturnPlatform.setOrderId(orderId);

        List<String> complaintsImages = (List<String>) map.get("sellerVoucher");
        String seller_voucher = JSON.toJSONString(complaintsImages);
        orderReturnPlatform.setSellerVoucher(seller_voucher);

        orderReturnPlatform.setSellerRemarks(String.valueOf(map.get("sellerRemarks")));

        orderReturnPlatform.setExpriationTime(calendarTime);
        orderReturnPlatform.setInterventionState(1);
        Integer integer = this.baseMapper.updateOrderReturnShop(orderReturnPlatform);

        this.baseMapper.updateOrderReturnState(orderId,calendarTime);
        if (integer > 0){
            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
    }

    @Override
    public ResponseResult callReturnOrder(Map<String, Object> map) {
        Map<String, Object> orderGoodsMap = new HashMap<String, Object>();
        String token = String.valueOf(map.get("token"));
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (userInfo == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        orderGoodsMap.put("returnCode", map.get("returnCode"));
        orderGoodsMap.put("returnShopHandle", 2);
        orderGoodsMap.put("returnState", 2);
        orderGoodsMap.put("callStatus", 1);

        String orderId = String.valueOf(map.get("orderId"));
        Map<String, Object> updateMap = new HashMap<String, Object>();
        updateMap.put("orderId", orderId);
        updateMap.put("orderReturnStatus", "1");
        Integer torf = this.baseMapper.updateOrderBaseById(updateMap);

        Map<String, Object> updateGoodsMap = new HashMap<String, Object>();
        updateGoodsMap.put("orderId", orderId);
        updateGoodsMap.put("goodsReturnStatus", 1);
        this.baseMapper.updateOrderGoodsById2(updateGoodsMap);
        //更新record表状态
        Map<String, String> feignMap = new HashMap<>();
        feignMap.put("orderId", orderId);
        feignMap.put("recordStatus", "8");
        this.baseMapper.updateRecordRefuse(feignMap);
        if (1 != torf) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(2, "唤起失败");
        }

        Integer torf1 = this.baseMapper.updateOrderReturnById(orderGoodsMap);
        if (1 == torf1) {
            return ResponseResult.success();
        }
        return ResponseResult.fail(2, "唤起失败");
    }

    @Override
    @GlobalTransactional
    public ResponseResult shopReturnShipping(Map<String, String> paraMap) {
        Map<String, Object> orderGoodsMap = new HashMap<String, Object>();
        Map<String, Object> orderBaseMap = new HashMap<String, Object>();

        // 卖家填写物流信息
        orderGoodsMap.put("returnCode", paraMap.get("returnCode"));
        // 退货物流单号
        orderGoodsMap.put("returnShippingCode", paraMap.get("returnShippingCode"));
        // 联系电话
        orderGoodsMap.put("returnMobile", paraMap.get("returnMobile"));
        // 物流id
        orderGoodsMap.put("returnPostCode", paraMap.get("returnPostCode"));
        orderGoodsMap.put("returnShopHandle", 4);
        // 订单状态
        orderGoodsMap.put("returnState", "4");
        // 更改唤醒状态
        orderGoodsMap.put("callStatus", 0);
        String logistics=String.valueOf(System.currentTimeMillis());
        String fillLogisticsTime=TimeStampUtil.stampToDate(logistics);
        orderGoodsMap.put("fillLogisticsTime", fillLogisticsTime);

        orderGoodsMap.put("returnShopTime", new Date());
        orderGoodsMap.put("returnShopMessage", paraMap.get("returnShopMessage"));
        orderGoodsMap.put("returnFinishTime", new Date());

        //	 商家确认收货该状态为9已退款
        String orderId = this.baseMapper.getOrderIdByReturnCode(paraMap.get("returnCode"));

        //查询用户售后商品
        List<Integer> returnGoods = this.baseMapper.queryReturnGoods(orderId);

        orderBaseMap.put("orderId",orderId);
        orderBaseMap.put("orderStatus","9");
        orderBaseMap.put("orderReturnStatus","2");
        orderBaseMap.put("orderRefundStatus","0");
        Integer torf = this.baseMapper.updateOrderBaseById(orderBaseMap);
        Map<String, Object> updateGoodsMap = new HashMap<String, Object>();

        updateGoodsMap.put("orderId",orderId);
        updateGoodsMap.put("goodsReturnStatus",2);
        updateGoodsMap.put("goodsRefundStatus",0);
        for (Integer returnGood : returnGoods) {
            updateGoodsMap.put("goodsId",returnGood);
            this.baseMapper.updateOrderGoodsById1(updateGoodsMap);
        }

        String uOrderId = this.baseMapper.queryPaymentNumber(orderId);
        OrderBaseEntity orderBaseEntity = orderBaseMapper.selectById(orderId);
        BigDecimal returnCash = this.baseMapper.queryReturnCash(orderId);

        List<Integer> orderTradeStatus = this.baseMapper.queryOrderRecordStatus(uOrderId);
        RefundParamDTO refundPara = new RefundParamDTO();
        boolean isRefundSuccess = false;
        if(torf == 1){
            refundPara = this.baseMapper.queryRefundPara(orderId);
            refundPara.setOrderTradeStatus(orderTradeStatus);
            refundPara.setReturnCash(returnCash);
            isRefundSuccess = waitShipmentsRefund(refundPara);

        }
        if(!isRefundSuccess){
            // 回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(2,"填写物流失败");
        }

        if (1 != torf ) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(2,"填写物流失败");
        }

        // 分销佣金订单处理
        commissionReturn(orderId,returnCash);
        //判断当前订单是否全部退货
        Boolean huoBaoreturn = true;
        //平台退货佣金计算  会员折扣计算
        List<OrderPingtaiCommissionDTO> orderPingtaiCommissions = this.baseMapper.queryOrderPingTaiCommission(orderId);
        BigDecimal countPingTaiCommission = new BigDecimal(0);
        BigDecimal huiYuanZhekou = new BigDecimal(0);
        for (OrderPingtaiCommissionDTO orderPingtaiCommission : orderPingtaiCommissions) {
            // 总的平台抽佣/下单数量 * 退单数量
            System.out.println(new BigDecimal(orderPingtaiCommission.getGoodsNum()));
//            //下单数量 等于 退单数量 平台抽佣全退
//            if (orderPingtaiCommission.getGoodsNum().equals(orderPingtaiCommission.getGoodsReturnNum())) {
//                countPingTaiCommission = countPingTaiCommission.add(orderPingtaiCommission.getOrderGoodsCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
//            } else {
//                BigDecimal goodsCount = orderPingtaiCommission.getOrderGoodsCommission().divide(new BigDecimal(orderPingtaiCommission.getGoodsNum()), 2, BigDecimal.ROUND_HALF_UP);
//                goodsCount = goodsCount.multiply(new BigDecimal(orderPingtaiCommission.getGoodsReturnNum())).setScale(2, BigDecimal.ROUND_HALF_UP);
//                countPingTaiCommission = countPingTaiCommission.add(goodsCount).setScale(2, BigDecimal.ROUND_HALF_UP);
//            }

            //计算会员折扣
            if (!orderPingtaiCommission.getGoodsNum().equals(orderPingtaiCommission.getGoodsReturnNum())) {
                huoBaoreturn = false;
            }
            //退还同步商品的 佣金
            if (null != orderPingtaiCommission.getDropShipping() && 1 == orderPingtaiCommission.getDropShipping()) {
                BigDecimal supperPrice = this.baseMapper.querySupperGoodsPrice(orderId);
                supperPrice = supperPrice.divide(new BigDecimal(orderPingtaiCommission.getGoodsNum()), 2, RoundingMode.HALF_UP);
                BigDecimal returnSupperPrice = supperPrice.multiply(new BigDecimal(orderPingtaiCommission.getGoodsReturnNum())).setScale(2, RoundingMode.HALF_UP);
                this.baseMapper.updateOrderRetuenSupperCommission(orderId, returnSupperPrice);
            }
        }
        //根据退款金额退多少佣金
        if (returnCash != null && orderBaseEntity.getOrderPaymentAmount().compareTo(returnCash) > 0) {
            BigDecimal lv = returnCash.divide(orderBaseEntity.getOrderPaymentAmount(), 2, RoundingMode.HALF_UP);
            countPingTaiCommission = BigDecimal.valueOf(orderBaseEntity.getOrderCommissionFee()).multiply(lv).setScale(2, RoundingMode.HALF_UP);
            huiYuanZhekou = BigDecimal.valueOf(orderBaseEntity.getBaseMemberDiscount()).multiply(lv).setScale(2, RoundingMode.HALF_UP);
        } else {
            countPingTaiCommission = BigDecimal.valueOf(orderBaseEntity.getOrderCommissionFee());
            huiYuanZhekou = BigDecimal.valueOf(orderBaseEntity.getBaseMemberDiscount());
        }
        //根据订单号查询支付单号 因为有可能多个订单公用一个支付单号 如果是多个订单共用用一个支付单号 要判断除当前退单外的其他订单是否是全退
        String paymentNumber = this.baseMapper.queryOrderPaymentNumber(orderId);
        //如果多个订单公用一个支付单号 根据当前订单号 和 支付单号 查询是否有其他订单没有全退货
        Integer notOrderNum  = this.baseMapper.queryNotRetuenOrder(orderId,paymentNumber);
        if(0 <= notOrderNum){
            //说明有其他订单没有完全退货 不退红包 优惠券
            huoBaoreturn = false;
        }
        //退货红包 优惠券
        if(huoBaoreturn){
            this.baseMapper.updateHongbaoStart(orderId);
            this.baseMapper.updateYouHuiquanStart(orderId);
        }
        this.baseMapper.updateOrderBasePingTaiCommission(orderId,countPingTaiCommission);
        //更新退款表 平台退还佣金 退还会员折扣
        this.baseMapper.updateOrderReturnPingTaiCommission(orderId,countPingTaiCommission,huiYuanZhekou);
        // 代发货订单 经销商和供应商佣金处理
        BigDecimal totalDealerCommission = BigDecimal.ZERO;
        BigDecimal totalSupplyCommission = BigDecimal.ZERO;
        List<OrderSupplyCommissionDTO> supplyCommissionList = this.baseMapper.queryOrderSupplyCommission(orderId);
        for(OrderSupplyCommissionDTO orderSupplyCommission : supplyCommissionList) {
            if(null != orderSupplyCommission.getOrderGoodsReturnnum()){
                // 退还的经销商和分销商佣金
                BigDecimal returnDealerCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(),2,
                        BigDecimal.ROUND_HALF_UP).multiply(orderSupplyCommission.getDealerCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
                BigDecimal returnSupplCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(),2,
                        BigDecimal.ROUND_HALF_UP).multiply(orderSupplyCommission.getSupplyCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
                orderSupplyCommission.setDealerReturnCommission(returnDealerCommission);
                orderSupplyCommission.setSupplyReturnCommission(returnSupplCommission);
                // 订单总的退还佣金
                totalDealerCommission = totalDealerCommission.add(returnDealerCommission);
                totalSupplyCommission = totalSupplyCommission.add(totalSupplyCommission);
            }
        }
        //更新商品订单退还佣金
        this.baseMapper.updateOrderGoodsCommissionBatch(supplyCommissionList);
        // 更新订单退还佣金
        this.baseMapper.updateOrderSupplyCommission(orderId,totalDealerCommission,totalSupplyCommission);
        Map<String,Object> goodsNumMap = new HashMap<>();
        List<Map<String,Object>> goodsNum = this.baseMapper.queryBuyNumByorderId(orderId);
        goodsNumMap.put("goodsNum",goodsNum);
        updateGoodsSalenum(goodsNumMap);//退款更新商品销量
        //根据orderid 查询应该回退的积分和userid
        Map<String, Object> map = this.baseMapper.queryAddpointsLogByOrderId(orderId);
        //ZZZ 新增积分按比例扣除逻辑
        //订单实付金额
        BigDecimal order_payment_amount = this.baseMapper.queryOrderAmount(orderId);
        //订单商品总价（不含运费）
        BigDecimal order_goods_amount = this.baseMapper.queryOrderGoodsAmount(orderId);
        //退货商品总价(不含运费）
        BigDecimal returnAmount = BigDecimal.ZERO;
        //退货积分系数
        BigDecimal coef = BigDecimal.ZERO;
        List<OrderReturnPointsDTO> orderReturnPointsList = this.baseMapper.queryOrderReturnInfo(orderId);
        if (null != orderReturnPointsList && orderReturnPointsList.size() > 0) {
            for (OrderReturnPointsDTO orp : orderReturnPointsList) {
                BigDecimal goodsPrice = null != orp ? orp.getGoodsPrice() : BigDecimal.ZERO;
                Integer goodsReturnNum = null != orp ? orp.getOrderGoodsReturnnum() : 0;
                returnAmount = returnAmount.add(goodsPrice.multiply(new BigDecimal(goodsReturnNum)));
            }
        }
        //实际退款金额(用于计算退还积分)
        returnAmount = returnAmount.multiply(order_payment_amount).divide(order_goods_amount, RoundingMode.HALF_UP);
        //实际退款积分ZZZ
        BigDecimal tmp = BigDecimal.ZERO;
        if (null != map && null != map.get("points_log_points")) {
            tmp = returnAmount.multiply(new BigDecimal((Integer) map.get("points_log_points")).divide(order_payment_amount, RoundingMode.HALF_UP));
        }
        Integer tmpInt = tmp.intValue();
        map.put("points_log_points", tmpInt);

        //插入我的余额明细表
        Map<String,Object> assetDetailMap = new HashMap<>();
        assetDetailMap.put("orderId",orderId);
        assetDetailMap.put("detailType",2);
        assetDetailMap.put("assetType",1);
        assetDetailMap.put("assetAmount",returnCash);
        AssetDirectionAndPayTypeInfoDTO assetInfo = this.baseMapper.getAssetDirectionAndPayTypeInfo(orderId);
        if(null != assetInfo){
            assetDetailMap.put("assetDirection",assetInfo.getAssetDirection());
            assetDetailMap.put("payType",assetInfo.getPayType());
            assetDetailMap.put("userId",assetInfo.getUserId());
            this.baseMapper.insertDetail(assetDetailMap);
        }

        //修改会员积分和会员等级
        MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
        ArrayList<String> list = new ArrayList<>();
        list.add((String) map.get("user_id"));
        updateMemberMessageListIntegral.setUserIdList(list);
        updateMemberMessageListIntegral.setIntegral((Integer) map.get("points_log_points"));
        //1是增加积分 0 是扣除积分
        updateMemberMessageListIntegral.setType(0);
        feignUpdateMemberIntegral(updateMemberMessageListIntegral);
        //添加积分修改记录
        UserPointLogParamDTO userPointLog = new UserPointLogParamDTO();
        userPointLog.setPointsLogType(2);
        userPointLog.setClassId(9);
        userPointLog.setPointsLogTime(new Date());
        userPointLog.setPointsLogDesc("商品退货");
        userPointLog.setPointsLogFlag("reg");
        userPointLog.setUserId((String) map.get("user_id"));
        userPointLog.setPointsLogPoints((Integer) map.get("points_log_points"));
        userPointLog.setPointsLogOperate("商品退货");
        userPointLog.setOrderId(orderId);
        this.baseMapper.feginAddpointsLog(userPointLog);

        Integer torf1 = this.baseMapper.updateOrderReturnById(orderGoodsMap);
        if (1 == torf1) {
            return ResponseResult.success(1,"填写物流成功");
        }
        // 回滚
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return ResponseResult.fail(2,"填写物流失败");
    }

    @Override
    public Boolean updateTimeOutReturn() {
        Map<String, Object> orderGoodsMap = new HashMap<String, Object>();
        Map<String, Object> orderBaseMap = new HashMap<String, Object>();
        Map<String, Object> assetDetailMap = new HashMap<>();
        ArrayList<Object> arrayList = new ArrayList<>();
        List<OrderReturnEntity> orderIds = this.baseMapper.queryTimeOutReturn();
        if (orderIds != null && orderIds.size() > 0) {
            for (OrderReturnEntity map1 : orderIds) {
                try {
                    Boolean is = true;
                    //查询店铺类型
                    Integer selectshoptype =  this.baseMapper.selectshoptype(map1.getShopId());

                    String orderId = map1.getOrderId();
                    String returnCode = map1.getReturnCode();
                    OrderBaseEntity orderBaseEntity=orderBaseMapper.selectById(orderId);
                    OrderReturnEntity orderReturnEntity=this.baseMapper.selectOne(new LambdaQueryWrapper<OrderReturnEntity>().eq(OrderReturnEntity::getOrderId,orderId));
                    OrderBaseEntity baseEntity = orderBaseMapper.selectById(orderId);
                    Integer orderStatus =orderBaseEntity.getOrderStatus();
                    Integer virtualGoods = 1;
                    //获取退货数量
                    Map<String, Object> goodsNumMap = new HashMap<>();
                    List<Map<String,Object>> goodsNum = this.baseMapper.queryBuyNumByorderId(orderId);
                    goodsNumMap.put("goodsNum", goodsNum);
                    //判断是否是虚拟订单 且没有被核销
                    OrderBaseEntity map = orderBaseMapper.selectOne(new LambdaQueryWrapper<OrderBaseEntity>()
                                          .eq(OrderBaseEntity::getOrderId,orderId)
                                          .eq(OrderBaseEntity::getVirtualGoods,0)
                                          .in(OrderBaseEntity::getIsCancel,1,2));
                    if (null != map) {
                        virtualGoods = 0;
                        //如果该虚拟订单已过期 且过期不退款直接返回false
                        Integer result = orderBaseMapper.queryisVirtualOrderByTime(orderId);
                        if (0 != result) {
                            return false;
                        }
                    }
                    BigDecimal returnCash = new BigDecimal(0);
                    if (orderStatus == 6) { //用户收到货物退款
                        orderGoodsMap.put("returnCode", returnCode);
                        // orderGoodsMap.put("orderId", paraMap.get("orderId"));
                        orderGoodsMap.put("returnShopHandle", 2);
                        //4-卖家收到货物
                        orderGoodsMap.put("returnState", 2);


                        //	 1.2修改商家同意订单状态为 6
                        orderBaseMap.put("orderId", orderId);
                        //9.已退款
                        orderBaseMap.put("orderStatus", "9");
                        //2是退款完成
                        orderBaseMap.put("orderRefundStatus", "2");
                        //2是退款完成
                        orderBaseMap.put("orderReturnStatus", "0");
                        Integer torf = orderBaseMapper.updateOrderBaseById(orderBaseMap);

                        orderGoodsMapper.update(null,new LambdaUpdateWrapper<OrderGoodsEntity>()
                                        .eq(OrderGoodsEntity::getOrderId,orderId)
                                        .set(OrderGoodsEntity::getGoodsRefundStatus,CommonType.orderRefundStatus.REFUND_COMPLETED.getCode())
                                        .set(OrderGoodsEntity::getGoodsReturnStatus,CommonType.orderReturnStatus.NO_RETURNS.getCode()));

                        String uOrderId =orderBaseEntity.getPaymentNumber();
                        returnCash = orderReturnEntity.getReturnCash();

                        List<Integer> orderTradeStatus = this.baseMapper.queryOrderRecordStatus(uOrderId);;
                        RefundParamDTO refundPara = new RefundParamDTO();
                        boolean isRefundSuccess = false;
                        if (torf == 1) {
                            refundPara = this.baseMapper.queryRefundPara(orderId);
                            refundPara.setOrderTradeStatus(orderTradeStatus);
                            refundPara.setReturnCash(returnCash);
                            refundPara.setShopId(map1.getShopId());
                            refundPara.setShopType(selectshoptype);
                            isRefundSuccess = waitShipmentsRefund(refundPara);
                            //退款更新商品销量
                            updateGoodsSalenum(goodsNumMap);
                        }
                        if (!isRefundSuccess) {
                            // 回滚
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return false;
                        }
                        if (1 != torf) {
                            // 回滚
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return false;
                        }
                        //未发货退款  虚拟商品订单可以进来
                    } else if (orderStatus == 3 || virtualGoods == 0) {
                        orderGoodsMap.put("returnCode", returnCode);
                        // orderGoodsMap.put("orderId", paraMap.get("orderId"));
                        orderGoodsMap.put("returnShopHandle", 2);
                        //卖家审核通过
                        orderGoodsMap.put("returnState", 2);
                        orderGoodsMap.put("returnFinishTime", DateUtils.getNowDate());

                        //	 1.2修改商家同意订单状态为 6
                        orderBaseMap.put("orderId", orderId);
                        //已退款
                        orderBaseMap.put("orderStatus", "9");
                        orderBaseMap.put("orderRefundStatus", "2");
                        orderBaseMap.put("orderReturnStatus", "0");
                        orderBaseMap.put("orderFinishedTime", DateUtils.getNowDate());
                        Integer torf =  this.baseMapper.updateOrderBaseById(orderBaseMap);
                        Map<String, Object> updateGoodsMap = new HashMap<String, Object>();
                        updateGoodsMap.put("orderId", orderId);
                        updateGoodsMap.put("goodsRefundStatus", 2);
                        updateGoodsMap.put("goodsReturnStatus", 0);
                        this.baseMapper.updateOrderGoodsById(updateGoodsMap);

                        String uOrderId =  this.baseMapper.queryPaymentNumber(orderId);
                        returnCash =  this.baseMapper.queryReturnCash(orderId);

                        List<Integer> orderTradeStatus =  this.baseMapper.queryOrderRecordStatus(uOrderId);
                        RefundParamDTO refundPara = new RefundParamDTO();
                        boolean isRefundSuccess = false;
                        if (torf == 1) {
                            refundPara = this.baseMapper.queryRefundPara(orderId);
                            refundPara.setOrderTradeStatus(orderTradeStatus);
                            refundPara.setReturnCash(returnCash);
                            refundPara.setShopId(map1.getShopId());
                            refundPara.setShopType(selectshoptype);
                            updateGoodsSalenum(goodsNumMap);
                            if (refundPara.getPayCode() != 12) {
                                isRefundSuccess =waitShipmentsRefund(refundPara);
                            } else {
                                isRefundSuccess = true;
                            }
                        }
                        if (!isRefundSuccess) {
                            // 回滚
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return false;
                        }
                        if (1 != torf) {
                            // 回滚
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return false;
                        }
                        //退款成功后 修改库存
                        //获取goodsid commonid 购买数量
                        List<WapGoodsSaleSumUpdateVO> wapGood = this.baseMapper.queryGoodsXinXi(orderId);
                        //封装数据
                        List<WapGoodsSaleSumDTO> wapGoodData = new ArrayList<>();
                        if (!CollectionUtils.isEmpty(wapGood)) {
                            wapGoodData = wapGood.stream().map(entity -> {
                                WapGoodsSaleSumDTO catResult = new WapGoodsSaleSumDTO();

                                BeanUtils.copyProperties(entity, catResult);
                                return catResult;
                            }).collect(Collectors.toList());
                        }
                        goodServiceClient.updateGoodsStock(wapGoodData);
                        for (WapGoodsSaleSumUpdateVO goods : wapGood) {
                            //遍历集合减去销量
                            this.baseMapper.lessgoodsBySales(goods);
                        }
                        //查询红包和代金卷
                        WapGoodsSaleSumUpdateVO wap =  this.baseMapper.queryRedByEnvelope(orderId);
                        if (null != wap) {
                            if (null != wap.getVoucherCode()) {
                                //退还代金卷
                                this.baseMapper.updateCouponStuate(wap.getVoucherCode());
                            }
                            if (null != wap.getRedpacketCode()) {
                                this.baseMapper.updateRedPageStuate(wap.getRedpacketCode());
                            }
                        }
                    } else {
                        is = false;
                    }
                    if (is) {
                        // 售后分销佣金处理
                        commissionReturn(orderId,returnCash);

                        // 代发货订单 经销商和供应商佣金处理
                        BigDecimal totalDealerCommission = BigDecimal.ZERO;
                        BigDecimal totalSupplyCommission = BigDecimal.ZERO;
                        List<OrderSupplyCommissionDTO> supplyCommissionList =  this.baseMapper.queryOrderSupplyCommission(orderId);
//			if (supplyCommissionList.size()>0) {
                        for (OrderSupplyCommissionDTO orderSupplyCommission : supplyCommissionList) {
                            if (null != orderSupplyCommission && !returnCash.equals(new BigDecimal("0.00"))) {
                                // 退还的经销商和分销商佣金
                                BigDecimal returnDealerCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(), 2, BigDecimal.ROUND_HALF_UP).multiply(orderSupplyCommission.getDealerCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                BigDecimal returnSupplCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(), 2, BigDecimal.ROUND_HALF_UP).multiply(orderSupplyCommission.getSupplyCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                orderSupplyCommission.setDealerReturnCommission(returnDealerCommission);
                                orderSupplyCommission.setSupplyReturnCommission(returnSupplCommission);
                                // 订单总的退还佣金
                                totalDealerCommission = totalDealerCommission.add(returnDealerCommission);
                                totalSupplyCommission = totalSupplyCommission.add(totalSupplyCommission);
                            }
                        }
//			}
                        // 由于退款 是全订单退款 所以退红包
                        this.baseMapper.updateHongbaoStart(orderId);
                        //更新商品订单退还佣金
                        this.baseMapper.updateOrderGoodsCommissionBatch(supplyCommissionList);
                        // 更新订单退还佣金
                        this.baseMapper.updateOrderSupplyCommission(orderId, totalDealerCommission, totalSupplyCommission);

                        //扣除分销佣金
                        Map<String, Object> mapFx =  orderReturnPlatformMapper.queryFXCommon(orderId);
                        if (null != mapFx) {
                            this.baseMapper.updateVKCommission(mapFx);
                        }
                        //插入我的余额明细表
                        assetDetailMap.put("orderId", orderId);
                        assetDetailMap.put("detailType", 2);
                        assetDetailMap.put("assetType", 1);
                        assetDetailMap.put("assetAmount", returnCash);
                        AssetDirectionAndPayTypeInfoDTO assetInfo =  this.baseMapper.getAssetDirectionAndPayTypeInfo(orderId);
                        if (null != assetInfo) {
                            assetDetailMap.put("assetDirection", assetInfo.getAssetDirection());
                            assetDetailMap.put("payType", assetInfo.getPayType());
                            assetDetailMap.put("userId", assetInfo.getUserId());
                            this.baseMapper.insertDetail(assetDetailMap);
                        }//判断是否是虚拟订单 且没有被核销
                        if (null != map) {
                            virtualGoods = 0;
                            //是否核销 0是 1否 2已过期
                            Integer isCancel =map.getIsCancel();
                            if (null != isCancel && 0 != isCancel) {
                                //如果该虚拟订单已过期 且过期不退款直接返回false
                                Integer result =  this.baseMapper.queryisVirtualOrderByTime(orderId);
                                if (0 != result) {
                                    return false;
                                }
                                boolean returnFlag = false;
                                //未核销且在有效期内
                                if (1 == isCancel) {
                                    Integer result1 =  this.baseMapper.queryisVirtualOrderByTime1(orderId);
                                    if (null != result1 && result1 > 0) {
                                        returnFlag = true;
                                    }
                                    //过期且可过期退款
                                } else if (2 == isCancel) {
                                    Integer result2 =  this.baseMapper.queryisVirtualOrderByTime2(orderId);
                                    if (null != result2 && result2 > 0) {
                                        returnFlag = true;
                                        //退还虚拟订单佣金
                                        //如果该虚拟订单已过期 且过期允许退款就扣除积分
                                        //扣减积分
                                        //修改会员积分和会员等级
                                        //根据orderid 查询应该回退的积分和userid
                                        Map<String, Object> tmpMap = this.baseMapper.queryAddpointsLogByOrderId(orderId);
                                        if (null != tmpMap) {
                                            MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
                                            ArrayList<String> list = new ArrayList<>();
                                            list.add((String) tmpMap.get("user_id"));
                                            updateMemberMessageListIntegral.setUserIdList(list);
                                            updateMemberMessageListIntegral.setIntegral((Integer) tmpMap.get("points_log_points"));
                                            //1是增加积分 0 是扣除积分
                                            updateMemberMessageListIntegral.setType(0);
                                            feignUpdateMemberIntegral(updateMemberMessageListIntegral);
                                            //添加积分修改记录
                                            UserPointLogParamDTO userPointLog = new UserPointLogParamDTO();
                                            userPointLog.setPointsLogType(2);
                                            userPointLog.setClassId(9);
                                            userPointLog.setPointsLogTime(new Date());
                                            userPointLog.setPointsLogDesc("商品退款");
                                            userPointLog.setPointsLogFlag("reg");
                                            userPointLog.setUserId(tmpMap.get("user_id").toString());
                                            userPointLog.setPointsLogPoints((Integer) tmpMap.get("points_log_points"));
                                            userPointLog.setPointsLogOperate("商品退款");
                                            userPointLog.setOrderId(orderId);
                                            this.baseMapper.feginAddpointsLog(userPointLog);
                                        }

                                    }
                                }
                                if (returnFlag) {
                                    Map<String, Object> dataMap =  this.baseMapper.queryOrderReturnInfoById(orderId);
                                    if (baseEntity.getOrderPaymentAmount().compareTo(returnCash) > 0) {
                                        BigDecimal lv = orderReturnEntity.getReturnCash().divide(baseEntity.getOrderPaymentAmount(), 2, RoundingMode.HALF_UP);
                                        if(baseEntity.getOrderCommissionFee() != null) {
                                            dataMap.put("orderCommissionFee", BigDecimal.valueOf(baseEntity.getOrderCommissionFee()).multiply(lv).setScale(2, RoundingMode.HALF_UP));
                                        }
                                        if(baseEntity.getBaseMemberDiscount() != null) {
                                            dataMap.put("baseMemberDiscount", BigDecimal.valueOf(baseEntity.getBaseMemberDiscount()).multiply(lv).setScale(2, RoundingMode.HALF_UP));
                                        }
                                        if(baseEntity.getDistributionDiscount() != null) {
                                            dataMap.put("distributionDiscount", baseEntity.getDistributionDiscount().multiply(lv).setScale(2, RoundingMode.HALF_UP));
                                        }
                                    }
                                    dataMap.put("orderId", orderId);
                                    this.baseMapper.updateOrderReturnInfoById(dataMap);
                                }
                            }
                        }
                        Integer torf =  this.baseMapper.updateOrderReturnById(orderGoodsMap);
                    }
                } catch (Exception e) {
                    arrayList.add(map1.getReturnCode());
                }
            }
        }
        return true;
    }

    @Override
    public Boolean updateTimeOutReturnGoods() {
        //商家超时未同意退货订单
        List<ReturnOrderDetailsVO> orderDetails = this.baseMapper.queryTimeOutReturnGoods();
        if (orderDetails != null && orderDetails.size() > 0){
            Map<String, Object> orderGoodsMap = new HashMap<String, Object>();
            for (ReturnOrderDetailsVO orderDetail : orderDetails) {
                String returnCode = orderDetail.getReturnCode();
                orderGoodsMap.put("returnCode", returnCode);
                //平台5
                orderGoodsMap.put("returnShopHandle", 2);
                orderGoodsMap.put("returnState", 2);
                //orderGoodsMap.put("returnAddrId", paraMap.get("returnAddrId"));
                orderGoodsMap.put("returnAddr", orderDetail.getOrderSellerAddress());
                orderGoodsMap.put("returnAddrName", orderDetail.getOrderSellerAddress());
                orderGoodsMap.put("returnRealName", orderDetail.getOrderSellerName());
                orderGoodsMap.put("returnNumber", orderDetail.getOrderSellerContact());
//				orderGoodsMap.put("returnShopMessage", paraMap.get("returnShopMessage"));
//				orderGoodsMap.put("returnShopTime", new Date());
                Calendar instance = Calendar.getInstance();
                instance.setTime(new Date());
                instance.add(Calendar.DATE,7);
                Date expiration_time = instance.getTime();

                orderGoodsMap.put("expirationTime", expiration_time);
                Integer torf = this.baseMapper.updateOrderReturnById(orderGoodsMap);
                orderGoodsMap.clear();
            }
        }

        //商家超时未收货退货订单
        List<ReturnOrderDetailsVO> timeoutorder =  this.baseMapper.queryTimeOutReturnGoods1();
        if (timeoutorder != null && timeoutorder.size() > 0){
            Map<String, Object> orderGoodsMap = new HashMap<String, Object>();
            Map<String, Object> orderBaseMap = new HashMap<String, Object>();
            for (ReturnOrderDetailsVO orderDetail : timeoutorder) {
                Integer selectshoptype = this.baseMapper.selectshoptype(orderDetail.getShopId());
                String returnCode = orderDetail.getReturnCode();
                orderGoodsMap.put("returnCode", returnCode);
                orderGoodsMap.put("returnShopHandle", 4);//4
                orderGoodsMap.put("returnState", 4);
                orderGoodsMap.put("returnShopTime", new Date());
                //orderGoodsMap.put("returnShopMessage", paraMap.get("returnShopMessage"));

                //	 商家确认收货该状态为9已退款
                OrderReturnEntity entity= this.baseMapper.selectOne(new LambdaQueryWrapper<OrderReturnEntity>()
                                          .eq(OrderReturnEntity::getReturnCode,returnCode));
                orderBaseMap.put("orderId", entity.getOrderId());
                orderBaseMap.put("orderStatus",CommonType.orderStatus.REFUNDED.getCode());
                orderBaseMap.put("orderReturnStatus",CommonType.orderReturnStatus.RETURN_COMPLETED.getCode());
                orderBaseMap.put("orderRefundStatus",CommonType.orderRefundStatus.NO_REFUND.getCode());
                Integer torf = orderBaseMapper.updateOrderBaseById(orderBaseMap);
                Map<String, Object> updateGoodsMap = new HashMap<String, Object>();
                updateGoodsMap.put("orderId",entity.getOrderId());
                updateGoodsMap.put("goodsReturnStatus",2);
                updateGoodsMap.put("goodsRefundStatus",0);
                orderGoodsMapper.updateOrderGoodsById2(updateGoodsMap);
                String uOrderId =  this.baseMapper.queryPaymentNumber(entity.getOrderId());
                OrderBaseEntity orderBaseEntity = orderBaseMapper.selectById(entity.getOrderId());
                BigDecimal returnCash= this.baseMapper.selectOne(new LambdaQueryWrapper<OrderReturnEntity>()
                        .eq(OrderReturnEntity::getOrderId,entity.getOrderId())).getReturnCash();


                List<Integer> orderTradeStatus = this.baseMapper.queryOrderRecordStatus(uOrderId);
                RefundParamDTO refundPara = new RefundParamDTO();
                boolean isRefundSuccess = false;
                if(torf == 1){
                    refundPara = this.baseMapper.queryRefundPara(entity.getOrderId());
                    refundPara.setOrderTradeStatus(orderTradeStatus);
                    refundPara.setReturnCash(returnCash);
                    refundPara.setShopId(orderDetail.getShopId());
                    refundPara.setShopType(selectshoptype);
                    isRefundSuccess=waitShipmentsRefund(refundPara);

                }
                if(!isRefundSuccess){
                    // 回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }

                if (1 != torf ) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }

                // 分销佣金订单处理
                commissionReturn(entity.getOrderId(),returnCash);
                //判断当前订单是否全部退货
                Boolean huoBaoreturn = true;
                //平台退货佣金计算  会员折扣计算
                List<OrderPingtaiCommissionDTO> orderPingtaiCommissions = this.baseMapper.queryOrderPingTaiCommission(entity.getOrderId());
                BigDecimal countPingTaiCommission = new BigDecimal(0);
                BigDecimal huiYuanZhekou = new BigDecimal(0);
                for (OrderPingtaiCommissionDTO orderPingtaiCommission : orderPingtaiCommissions) {
                    // 总的平台抽佣/下单数量 * 退单数量
                    System.out.println(new BigDecimal(orderPingtaiCommission.getGoodsNum()));
                    //下单数量 等于 退单数量 平台抽佣全退
//                    if(orderPingtaiCommission.getGoodsNum().equals(orderPingtaiCommission.getGoodsReturnNum())){
//                        countPingTaiCommission = countPingTaiCommission.add(orderPingtaiCommission.getOrderGoodsCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
//                    }else{
//                        BigDecimal goodsCount = orderPingtaiCommission.getOrderGoodsCommission().divide(new BigDecimal(orderPingtaiCommission.getGoodsNum()),2, BigDecimal.ROUND_HALF_UP);
//                        goodsCount = goodsCount.multiply(new BigDecimal(orderPingtaiCommission.getGoodsReturnNum())).setScale(2, BigDecimal.ROUND_HALF_UP);
//                        countPingTaiCommission = countPingTaiCommission.add(goodsCount).setScale(2, BigDecimal.ROUND_HALF_UP);
//                    }

                    //计算会员折扣
//                    BigDecimal zhekou = orderPingtaiCommission.getGoodsMemberDiscount().divide(new  BigDecimal(orderPingtaiCommission.getGoodsNum()),2, BigDecimal.ROUND_HALF_UP);
//                    zhekou = zhekou.multiply(new BigDecimal(orderPingtaiCommission.getGoodsReturnNum())).setScale(2, BigDecimal.ROUND_HALF_UP);
//                    huiYuanZhekou = huiYuanZhekou.add(zhekou).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if(!orderPingtaiCommission.getGoodsNum().equals(orderPingtaiCommission.getGoodsReturnNum())){
                        huoBaoreturn = false;
                    }
                    //退还同步商品的 佣金
                    if(null != orderPingtaiCommission.getDropShipping() && 1 == orderPingtaiCommission.getDropShipping()){
                        BigDecimal supperPrice = this.baseMapper.querySupperGoodsPrice(entity.getOrderId());
                        supperPrice = supperPrice.divide(new BigDecimal(orderPingtaiCommission.getGoodsNum()),2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal returnSupperPrice = supperPrice.multiply(new BigDecimal(orderPingtaiCommission.getGoodsReturnNum())).setScale(2, BigDecimal.ROUND_HALF_UP);
                        this.baseMapper.updateOrderRetuenSupperCommission(entity.getOrderId(),returnSupperPrice);
                    }
                }
                //根据退款金额退多少佣金
                if (orderBaseEntity.getOrderPaymentAmount().compareTo(returnCash) > 0) {
                    BigDecimal lv = returnCash.divide(orderBaseEntity.getOrderPaymentAmount(), 2, RoundingMode.HALF_UP);
                    countPingTaiCommission = BigDecimal.valueOf(orderBaseEntity.getOrderCommissionFee()).multiply(lv).setScale(2, RoundingMode.HALF_UP);
                    huiYuanZhekou = BigDecimal.valueOf(orderBaseEntity.getBaseMemberDiscount()).multiply(lv).setScale(2, RoundingMode.HALF_UP);
                } else {
                    countPingTaiCommission = BigDecimal.valueOf(orderBaseEntity.getOrderCommissionFee());
                    huiYuanZhekou = BigDecimal.valueOf(orderBaseEntity.getBaseMemberDiscount());
                }
                //根据订单号查询支付单号 因为有可能多个订单公用一个支付单号 如果是多个订单共用用一个支付单号 要判断除当前退单外的其他订单是否是全退
                String paymentNumber =  this.baseMapper.queryOrderPaymentNumber(entity.getOrderId());
                //如果多个订单公用一个支付单号 根据当前订单号 和 支付单号 查询是否有其他订单没有全退货
                Integer notOrderNum  =  this.baseMapper.queryNotRetuenOrder(entity.getOrderId(),paymentNumber);
                if(0 <= notOrderNum){
                    //说明有其他订单没有完全退货 不退红包 优惠券
                    huoBaoreturn = false;
                }
                //退货红包 优惠券
                if(huoBaoreturn){
                    this.baseMapper.updateHongbaoStart(entity.getOrderId());
                    this.baseMapper.updateYouHuiquanStart(entity.getOrderId());
                }
                this.baseMapper.updateOrderBasePingTaiCommission(entity.getOrderId(),countPingTaiCommission);
                //更新退款表 平台退还佣金 退还会员折扣
                this.baseMapper.updateOrderReturnPingTaiCommission(entity.getOrderId(),countPingTaiCommission,huiYuanZhekou);
                // 代发货订单 经销商和供应商佣金处理
                BigDecimal totalDealerCommission = BigDecimal.ZERO;
                BigDecimal totalSupplyCommission = BigDecimal.ZERO;
                List<OrderSupplyCommissionDTO> supplyCommissionList =  this.baseMapper.queryOrderSupplyCommission(entity.getOrderId());
                for(OrderSupplyCommissionDTO orderSupplyCommission : supplyCommissionList) {
                    if(null != orderSupplyCommission.getOrderGoodsReturnnum()){
                        // 退还的经销商和分销商佣金
                        BigDecimal returnDealerCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(),2, BigDecimal.ROUND_HALF_UP).multiply(orderSupplyCommission.getDealerCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal returnSupplCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(),2, BigDecimal.ROUND_HALF_UP).multiply(orderSupplyCommission.getSupplyCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
                        orderSupplyCommission.setDealerReturnCommission(returnDealerCommission);
                        orderSupplyCommission.setSupplyReturnCommission(returnSupplCommission);
                        // 订单总的退还佣金
                        totalDealerCommission = totalDealerCommission.add(returnDealerCommission);
                        totalSupplyCommission = totalSupplyCommission.add(totalSupplyCommission);
                    }
                }
                //扣除分销佣金
                Map<String,Object> mapFx = orderReturnPlatformMapper.queryFXCommon(entity.getOrderId());
                if(null != mapFx){
                    this.baseMapper.updateVKCommission(mapFx);
                }
                //更新商品订单退还佣金
                this.baseMapper.updateOrderGoodsCommissionBatch(supplyCommissionList);
                // 更新订单退还佣金
                this.baseMapper.updateOrderSupplyCommission(entity.getOrderId(),totalDealerCommission,totalSupplyCommission);
                Map<String,Object> goodsNumMap = new HashMap<>();
                List<Map<String,Object>> goodsNum =  this.baseMapper.queryBuyNumByorderId(entity.getOrderId());
                goodsNumMap.put("goodsNum",goodsNum);
                //退款更新商品销量
                updateGoodsSalenum(goodsNumMap);
                //根据orderid 查询应该回退的积分和userid
                Map<String, Object> map =this.baseMapper.queryAddpointsLogByOrderId(entity.getOrderId());
                if (map == null){
                    map = new HashMap<String, Object>();
                }
                //ZZZ 新增积分按比例扣除逻辑
                //订单实付金额
                BigDecimal order_payment_amount = this.baseMapper.queryOrderAmount(entity.getOrderId());
                //订单商品总价（不含运费）
                BigDecimal order_goods_amount = this.baseMapper.queryOrderGoodsAmount(entity.getOrderId());
                BigDecimal returnAmount = BigDecimal.ZERO;//退货商品总价(不含运费）
                BigDecimal coef = BigDecimal.ZERO;//退货积分系数
                List<OrderReturnPointsDTO> orderReturnPointsList = this.baseMapper.queryOrderReturnInfo(entity.getOrderId());
                if (null != orderReturnPointsList && orderReturnPointsList.size() > 0) {
                    for (OrderReturnPointsDTO orp : orderReturnPointsList) {
                        BigDecimal goodsPrice = null != orp ? orp.getGoodsPrice() : BigDecimal.ZERO;
                        Integer goodsReturnNum = null != orp ? orp.getOrderGoodsReturnnum() : 0;
                        returnAmount = returnAmount.add(goodsPrice.multiply(new BigDecimal(goodsReturnNum)));
                    }
                }
                //实际退款金额(用于计算退还积分)
                returnAmount = returnAmount.multiply(order_payment_amount).divide(order_goods_amount, RoundingMode.HALF_UP);
                //实际退款积分ZZZ
                BigDecimal tmp = BigDecimal.ZERO;
                if (null != map && null != map.get("points_log_points")) {
                    tmp = returnAmount.multiply(new BigDecimal((Integer) map.get("points_log_points"))).divide(order_payment_amount, RoundingMode.HALF_UP);
                }
                Integer tmpInt = tmp.intValue();
                map.put("points_log_points", tmpInt);

                //插入我的余额明细表
                Map<String,Object> assetDetailMap = new HashMap<>();
                assetDetailMap.put("orderId",entity.getOrderId());
                assetDetailMap.put("detailType",2);
                assetDetailMap.put("assetType",1);
                assetDetailMap.put("assetAmount",returnCash);
                AssetDirectionAndPayTypeInfoDTO assetInfo = this.baseMapper.getAssetDirectionAndPayTypeInfo(entity.getOrderId());
                if(null != assetInfo){
                    assetDetailMap.put("assetDirection",assetInfo.getAssetDirection());
                    assetDetailMap.put("payType",assetInfo.getPayType());
                    assetDetailMap.put("userId",assetInfo.getUserId());
                    this.baseMapper.insertDetail(assetDetailMap);
                }

                //修改会员积分和会员等级
                MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
                ArrayList<String> list = new ArrayList<>();
                list.add((String) map.get("user_id"));
                updateMemberMessageListIntegral.setUserIdList(list);
                updateMemberMessageListIntegral.setIntegral((Integer) map.get("points_log_points"));
                //1是增加积分 0 是扣除积分
                updateMemberMessageListIntegral.setType(0);
                feignUpdateMemberIntegral(updateMemberMessageListIntegral);
                //添加积分修改记录
                UserPointLogParamDTO userPointLog = new UserPointLogParamDTO();
                userPointLog.setPointsLogType(2);
                userPointLog.setClassId(9);
                userPointLog.setPointsLogTime(new Date());
                userPointLog.setPointsLogDesc("商品退货");
                userPointLog.setPointsLogFlag("reg");
                userPointLog.setUserId(map.get("user_id").toString());
                userPointLog.setPointsLogPoints((Integer) map.get("points_log_points"));
                userPointLog.setPointsLogOperate("商品退货");
                userPointLog.setOrderId(entity.getOrderId());
                this.baseMapper.feginAddpointsLog(userPointLog);

                orderGoodsMap.put("returnFinishTime",new Date());
                this.baseMapper.updateOrderReturnById(orderGoodsMap);
                orderGoodsMap.clear();
                orderBaseMap.clear();
            }
        }
        return true;
    }

    @Override
    public Boolean updateTimeOutBuyReturn() {
        List<ReturnOrderDetailVO> returnOrderDetails = this.baseMapper.updateTimeOutBuyReturn();
        if (returnOrderDetails != null && returnOrderDetails.size() > 0){
            Map orderGoodsMap = new HashMap();
            for (ReturnOrderDetailVO returnOrderDetail : returnOrderDetails) {
                String returnCode = returnOrderDetail.getReturnCode();
                String orderId = returnOrderDetail.getOrderId();
                // 超时关闭
                orderGoodsMap.put("returnCode", returnCode);
                orderGoodsMap.put("returnShopHandle", 8);
                orderGoodsMap.put("returnState", 8);
                orderGoodsMap.put("closeTime", new Date());
                Map<String, Object> updateMap = new HashMap<String, Object>();
                Map<String, Object> updateGoodsMap = new HashMap<String, Object>();
                Integer torfOne = null;
                Integer torfTwo = null;
                updateMap.put("orderId", orderId);
                // 原值：2，现改为0，用户可持续申请
                updateMap.put("orderRefundStatus", "0");
                // 原值：2，现改为0，用户可持续申请
                updateMap.put("goodsReturnStatus", "0");

                updateGoodsMap.put("orderId",orderId);

                updateGoodsMap.put("goodsReturnStatus",0);
                updateGoodsMap.put("goodsRefundStatus",0);
                //添加商家拒绝退款时间
                String businessTime =String.valueOf(System.currentTimeMillis());
                String businessRefundTime=DateUtils.stampToDate(businessTime);

                updateGoodsMap.put("businessRefundTime",businessRefundTime);

                torfOne = orderBaseMapper.updateOrderBaseById(updateMap);

                //更新record表状态
                Map<String,String> feignMap = new HashMap<>();
                feignMap.put("orderId",orderId);
                // 原值：7
                feignMap.put("recordStatus", CommonType.recordStatus.REFUNDING.getCode().toString());
                payMentServiceClient.updateRefuse(feignMap);

                if (1 != torfOne ) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
                Integer torf = this.baseMapper.updateOrderReturnById(orderGoodsMap);
                orderGoodsMap.clear();
            }
        }
        return true;
    }

    @Override
    public Boolean updatebuyTimeOutReturn() {
        List<ReturnOrderDetailVO> orderDetails = this.baseMapper.updatebuyTimeOutReturn();
        if (orderDetails != null && orderDetails.size() > 0){
            Map orderGoodsMap = new HashMap();
            Map updateGoodsMap = new HashMap();
            for (ReturnOrderDetailVO orderDetail : orderDetails) {
                String returnCode = orderDetail.getReturnCode();
                String orderId = orderDetail.getOrderId();
                orderGoodsMap.put("returnCode", returnCode);
                orderGoodsMap.put("returnShopHandle", 13);
                orderGoodsMap.put("returnState", 13);

                orderGoodsMap.put("orderId", orderId);
                Calendar instance = Calendar.getInstance();
                instance.setTime(new Date());
                instance.add(Calendar.DATE,1);
                Date expiration_time = instance.getTime();
                orderGoodsMap.put("expirationTime", expiration_time);
                this.baseMapper.updateOrderBaseById1(orderGoodsMap);

                updateGoodsMap.put("orderId",orderId);
                updateGoodsMap.put("goodsReturnStatus",0);
                updateGoodsMap.put("goodsRefundStatus",0);
                //returnMoneyDao.updateOrderGoodsById2(updateGoodsMap);

                Map<String, Object> updateMap = new HashMap<String, Object>();
                updateMap.put("orderId", orderId);
                updateMap.put("orderRefundStatus","0");
                updateMap.put("orderReturnStatus","0");
                Integer torf = orderBaseMapper.updateOrderBaseById(updateMap);
                if (1 != torf) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
            }

            Integer torf =  this.baseMapper.updateOrderReturnById(orderGoodsMap);
            orderGoodsMap.clear();
            updateGoodsMap.clear();
        }
        return true;
    }


    public Boolean retForSellerReceiveBoolean(Map<String, String> paraMap) {
        Map<String, Object> orderGoodsMap = new HashMap<>();
        Map<String, Object> orderBaseMap = new HashMap<>();

        // 商家同意
        if (1 == Integer.parseInt(paraMap.get("type"))) {
            orderGoodsMap.put("returnCode", paraMap.get("returnCode"));
            orderGoodsMap.put("returnShopHandle", 4);
            orderGoodsMap.put("returnState", 4);
            orderGoodsMap.put("returnShopTime", new Date());
            orderGoodsMap.put("returnShopMessage", paraMap.get("returnShopMessage"));
            orderGoodsMap.put("returnFinishTime", new Date());

            //	 商家确认收货该状态为9已退款
            String orderId = this.baseMapper.getOrderIdByReturnCode(paraMap.get("returnCode"));

            //查询用户售后商品
            List<Integer> returnGoods = this.baseMapper.queryReturnGoods(orderId);

            orderBaseMap.put("orderId",orderId);
            orderBaseMap.put("orderStatus","9");
            orderBaseMap.put("orderReturnStatus","2");
            orderBaseMap.put("orderRefundStatus","0");
            Integer torf = this.baseMapper.updateOrderBaseById(orderBaseMap);
            Map<String, Object> updateGoodsMap = new HashMap<String, Object>();

            updateGoodsMap.put("orderId",orderId);
            updateGoodsMap.put("goodsReturnStatus",2);
            updateGoodsMap.put("goodsRefundStatus",0);
            for (Integer returnGood : returnGoods) {
                updateGoodsMap.put("goodsId",returnGood);
                this.baseMapper.updateOrderGoodsById1(updateGoodsMap);
            }

            String uOrderId = this.baseMapper.queryPaymentNumber(orderId);
            OrderBaseEntity orderBaseEntity = orderBaseMapper.selectById(orderId);
            BigDecimal returnCash = this.baseMapper.queryReturnCash(orderId);

            List<Integer> orderTradeStatus = this.baseMapper.queryOrderRecordStatus(uOrderId);
            boolean isRefundSuccess = false;
            if(torf == 1){
                RefundParamDTO refundPara = this.baseMapper.queryRefundPara(orderId);
                refundPara.setOrderTradeStatus(orderTradeStatus);
                refundPara.setReturnCash(returnCash);
                refundPara.setShopType(Integer.valueOf(paraMap.get("shopType")));
                refundPara.setShopId(Integer.valueOf(paraMap.get("shopId")));
                isRefundSuccess = waitShipmentsRefund(refundPara);

            }
            if(!isRefundSuccess){
                // 回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }

            if (1 != torf ) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }

            // 分销佣金订单处理
            commissionReturn(orderId,returnCash);
            //判断当前订单是否全部退货
            Boolean huoBaoreturn = true;
            //平台退货佣金计算  会员折扣计算
            List<OrderPingtaiCommissionDTO> orderPingtaiCommissions = this.baseMapper.queryOrderPingTaiCommission(orderId);
            BigDecimal countPingTaiCommission = new BigDecimal(0);
            BigDecimal huiYuanZhekou = new BigDecimal(0);
            for (OrderPingtaiCommissionDTO orderPingtaiCommission : orderPingtaiCommissions) {
                // 总的平台抽佣/下单数量 * 退单数量
                System.out.println(new BigDecimal(orderPingtaiCommission.getGoodsNum()));
                //下单数量 等于 退单数量 平台抽佣全退
//                if (orderPingtaiCommission.getGoodsNum().equals(orderPingtaiCommission.getGoodsReturnNum())) {
//                    countPingTaiCommission = countPingTaiCommission.add(orderPingtaiCommission.getOrderGoodsCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
//                } else {
//                    BigDecimal goodsCount = orderPingtaiCommission.getOrderGoodsCommission().divide(new BigDecimal(orderPingtaiCommission.getGoodsNum()), 2, BigDecimal.ROUND_HALF_UP);
//                    goodsCount = goodsCount.multiply(new BigDecimal(orderPingtaiCommission.getGoodsReturnNum())).setScale(2, BigDecimal.ROUND_HALF_UP);
//                    countPingTaiCommission = countPingTaiCommission.add(goodsCount).setScale(2, BigDecimal.ROUND_HALF_UP);
//                }

                //计算会员折扣
                if (!orderPingtaiCommission.getGoodsNum().equals(orderPingtaiCommission.getGoodsReturnNum())) {
                    huoBaoreturn = false;
                }
                //退还同步商品的 佣金
                if (null != orderPingtaiCommission.getDropShipping() && 1 == orderPingtaiCommission.getDropShipping()) {
                    BigDecimal supperPrice = this.baseMapper.querySupperGoodsPrice(orderId);
                    supperPrice = supperPrice.divide(new BigDecimal(orderPingtaiCommission.getGoodsNum()), 2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal returnSupperPrice = supperPrice.multiply(new BigDecimal(orderPingtaiCommission.getGoodsReturnNum())).setScale(2, BigDecimal.ROUND_HALF_UP);
                    this.baseMapper.updateOrderRetuenSupperCommission(orderId, returnSupperPrice);
                }
            }
            //根据退款金额退多少佣金
            if (orderBaseEntity.getOrderPaymentAmount().compareTo(returnCash) > 0) {
                BigDecimal lv = returnCash.divide(orderBaseEntity.getOrderPaymentAmount(), 2, RoundingMode.HALF_UP);
                countPingTaiCommission = BigDecimal.valueOf(orderBaseEntity.getOrderCommissionFee()).multiply(lv).setScale(2, RoundingMode.HALF_UP);
                huiYuanZhekou = BigDecimal.valueOf(orderBaseEntity.getBaseMemberDiscount()).multiply(lv).setScale(2, RoundingMode.HALF_UP);
            } else {
                countPingTaiCommission = BigDecimal.valueOf(orderBaseEntity.getOrderCommissionFee());
                huiYuanZhekou = BigDecimal.valueOf(orderBaseEntity.getBaseMemberDiscount());
            }
            //退还红包优惠卷
            returnred(orderId,returnCash,returnGoods);

            this.baseMapper.updateOrderBasePingTaiCommission(orderId,countPingTaiCommission);
            //更新退款表 平台退还佣金 退还会员折扣
            this.baseMapper.updateOrderReturnPingTaiCommission(orderId,countPingTaiCommission,huiYuanZhekou);
            // 代发货订单 经销商和供应商佣金处理
            BigDecimal totalDealerCommission = BigDecimal.ZERO;
            BigDecimal totalSupplyCommission = BigDecimal.ZERO;
            List<OrderSupplyCommissionDTO> supplyCommissionList = this.baseMapper.queryOrderSupplyCommission(orderId);
            for(OrderSupplyCommissionDTO orderSupplyCommission : supplyCommissionList) {
                if(null != orderSupplyCommission.getOrderGoodsReturnnum()){
                    // 退还的经销商和分销商佣金
                    BigDecimal returnDealerCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(),2,
                            BigDecimal.ROUND_HALF_UP).multiply(orderSupplyCommission.getDealerCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal returnSupplCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(),2,
                            BigDecimal.ROUND_HALF_UP).multiply(orderSupplyCommission.getSupplyCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
                    orderSupplyCommission.setDealerReturnCommission(returnDealerCommission);
                    orderSupplyCommission.setSupplyReturnCommission(returnSupplCommission);
                    // 订单总的退还佣金
                    totalDealerCommission = totalDealerCommission.add(returnDealerCommission);
                    totalSupplyCommission = totalSupplyCommission.add(totalSupplyCommission);
                }
            }
            //更新商品订单退还佣金
            this.baseMapper.updateOrderGoodsCommissionBatch(supplyCommissionList);
            // 更新订单退还佣金
            this.baseMapper.updateOrderSupplyCommission(orderId,totalDealerCommission,totalSupplyCommission);
            Map<String,Object> goodsNumMap = new HashMap<>();
            List<Map<String,Object>> goodsNum = this.baseMapper.queryBuyNumByorderId(orderId);
            //买家id
            String buyerUserId = goodsNum.get(0).get("buyer_user_id").toString();
            goodsNumMap.put("goodsNum",goodsNum);
            //退款更新商品销量
            updateGoodsSalenum(goodsNumMap);
            //根据orderid 查询应该回退的积分和userid
            Map<String, Object> map = this.baseMapper.queryAddpointsLogByOrderId(orderId);
            //ZZZ 新增积分按比例扣除逻辑
            //订单实付金额
            BigDecimal order_payment_amount = this.baseMapper.queryOrderAmount(orderId);
            //订单退款金额
            BigDecimal returnAmount = returnCash;
            BigDecimal tmp = BigDecimal.ZERO;
            if (null != map && null != map.get("points_log_points")) {
                tmp = returnAmount.multiply(new BigDecimal((Integer) map.get("points_log_points")).divide(order_payment_amount, RoundingMode.HALF_UP));
            }
            Integer tmpInt = tmp.intValue();
            map.put("points_log_points", tmpInt);

            //插入我的余额明细表
            Map<String,Object> assetDetailMap = new HashMap<>();
            assetDetailMap.put("orderId",orderId);
            assetDetailMap.put("detailType",2);
            assetDetailMap.put("assetType",1);
            assetDetailMap.put("assetAmount",returnCash);
            AssetDirectionAndPayTypeInfoDTO assetInfo = this.baseMapper.getAssetDirectionAndPayTypeInfo(orderId);
            if(null != assetInfo){
                assetDetailMap.put("assetDirection",assetInfo.getAssetDirection());
                assetDetailMap.put("payType",assetInfo.getPayType());
                assetDetailMap.put("userId",assetInfo.getUserId());
                this.baseMapper.insertDetail(assetDetailMap);
            }

            //修改会员积分和会员等级
            MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
            ArrayList<String> list = new ArrayList<>();
            list.add(String.valueOf(map.get("user_id")));
            updateMemberMessageListIntegral.setUserIdList(list);
            updateMemberMessageListIntegral.setIntegral((Integer) map.get("points_log_points"));
            //1是增加积分 0 是扣除积分
            updateMemberMessageListIntegral.setType(0);
            feignUpdateMemberIntegral(updateMemberMessageListIntegral);
            //添加积分修改记录
            UserPointLogParamDTO userPointLog = new UserPointLogParamDTO();
            userPointLog.setPointsLogType(2);
            userPointLog.setClassId(9);
            userPointLog.setPointsLogTime(new Date());
            userPointLog.setPointsLogDesc("商品退货");
            userPointLog.setPointsLogFlag("reg");
            userPointLog.setUserId(map.get("user_id").toString());
            userPointLog.setPointsLogPoints((Integer) map.get("points_log_points"));
            userPointLog.setPointsLogOperate("商品退货");
            userPointLog.setOrderId(orderId);
            this.baseMapper.feginAddpointsLog(userPointLog);
            //罚扣质保金
            charging(orderId,returnGoods,paraMap.get("userId"),Integer.valueOf(paraMap.get("shopId")));
            //退回plus折扣额度
            try {
                orderBaseService.plusdis(orderId,buyerUserId,returnGoods);
            } catch (ParseException e) {
            }
        } else {
            // 商家不同意
            orderGoodsMap.put("returnCode", paraMap.get("returnCode"));
            orderGoodsMap.put("returnShopMessage", paraMap.get("returnShopMessage"));
            orderGoodsMap.put("returnShopHandle", 10);
            orderGoodsMap.put("returnState", 10);
            orderGoodsMap.put("returnShopTime", new Date());
            Calendar instance = Calendar.getInstance();
            instance.setTime(new Date());
            instance.add(Calendar.DATE,2);
            Date expirationTime = instance.getTime();
            orderGoodsMap.put("expirationTime", expirationTime);

            String orderId = this.baseMapper.getOrderIdByReturnCode(paraMap.get("returnCode"));
            Map<String, Object> updateMap = new HashMap<>();
            updateMap.put("orderId", orderId);
            updateMap.put("orderReturnStatus", "3");
            updateMap.put("orderRefundStatus", "0");
            Integer torf = this.baseMapper.updateOrderBaseById(updateMap);
            Map<String, Object> updateGoodsMap = new HashMap<>();

            //查询用户售后商品
            List<Integer> returnGoods = this.baseMapper.queryReturnGoods(orderId);

            updateGoodsMap.put("orderId",orderId);
            updateGoodsMap.put("goodsReturnStatus",3);
            updateGoodsMap.put("orderRefundStatus",0);
            for (Integer returnGood : returnGoods) {
                updateGoodsMap.put("goodsId",returnGood);
                this.baseMapper.updateOrderGoodsById1(updateGoodsMap);
            }
            //更新record表状态
            Map<String,String> feignMap = new HashMap<>();
            feignMap.put("orderId",orderId);
            feignMap.put("recordStatus","7");
            this.baseMapper.updateRefuse(feignMap);

            if (1 != torf ) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        }
        Integer torf = this.baseMapper.updateOrderReturnById(orderGoodsMap);
        if (1 == torf) {
            return true;
        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    public void commissionReturn(String orderId , BigDecimal returnMoney){
        try {
            OrderCommissionVO orderCommission = orderCommissionMapper.selectByPrimaryKey(orderId);
            if (null != orderCommission) {
                BigDecimal returnTgCommission = returnMoney.divide(orderCommission.getOrderPrice()).multiply(orderCommission.getTgCommission())
                        .setScale(2, BigDecimal.ROUND_HALF_UP);
                BigDecimal returnFxCommission = returnMoney.divide(orderCommission.getOrderPrice()).multiply(orderCommission.getFxCommission())
                        .setScale(2, BigDecimal.ROUND_HALF_UP);
                OrderCommissionVO updateOrderCommission = new OrderCommissionVO(orderId, CommonType.CommissionOrderStatus.RETURN.getCode(), returnMoney,
                        returnTgCommission, returnFxCommission);
                orderCommissionMapper.updateByPrimaryKeySelective(updateOrderCommission);

                // 员工用户退款金额更新
                ShopYgUserInfoDTO shopYgUserInfo = new ShopYgUserInfoDTO(orderCommission.getShareUserId(),returnMoney.doubleValue()+"");
                this.baseMapper.updateUserShareReturn(shopYgUserInfo);

                // 减去分享商品销售数量
                FxGoodsInfoDTO fxGoodsInfo = new FxGoodsInfoDTO(orderCommission.getGoodsNum().toString(),null,orderCommission.getGoodsId());
                this.baseMapper.updateGoodsSaleNum(fxGoodsInfo);

                // 更新微客用户佣金业绩
                VKUserDTO vkUser = new VKUserDTO(orderCommission.getShareUserId(),returnTgCommission.doubleValue()+"",returnFxCommission.doubleValue()+"");
                this.baseMapper.updateVkCommissionReturn(vkUser);
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    @Override
    public boolean waitShipmentsRefund(RefundParamDTO refundPara) {
        //查询支付配置信息
        selectYFPayConfig();
        System.out.println("======进入待发货退款=====");
        boolean flag = false;
        String orderId = refundPara.getOrderId();
        String refundOrderId = refundPara.getReturnCode();
        Integer payCode = refundPara.getPayCode();
        Integer orderFrom = refundPara.getOrderFrom();
        String paymentOtherNumber = refundPara.getPaymentOtherNumber();
        // 退款共用
        List<GroupBookingParamDTO> gbpList = this.baseMapper.queryRefundConsumeRecordMoney(orderId);

        String userId = null;
        String uOrderId = null;
        BigDecimal money = gbpList.get(0).getRecordMoney();
        // 退款金额
        // 总金额
        BigDecimal allMoney = BigDecimal.ZERO;
        BigDecimal AllTradePaymentRechargeCard = BigDecimal.ZERO;

        for (int i = 0; i < gbpList.size(); i++) {
            Integer type = 1;
            Integer userType = 3;
            if (userType.intValue() == gbpList.get(i).getUserType()) {
                // 当userType为 3 时，此订单为合并支付
                userId = gbpList.get(i).getUserId();
                // 合并支付订单号
                uOrderId = gbpList.get(i).getOrderId();
                // 合并支付总金额
                allMoney = gbpList.get(i).getRecordMoney();
            } else if (type.intValue() == gbpList.get(i).getUserType()) {
                // 其他情况，正常取值
                userId = gbpList.get(i).getUserId();
                uOrderId = gbpList.get(i).getOrderId();
                // 计算订单总金额
                allMoney = this.baseMapper.calculateAllOrderMoney(uOrderId);
                AllTradePaymentRechargeCard = this.baseMapper.queryAllTradePaymentRechargeCard(uOrderId);
            }
        }
        if(null == allMoney){
            allMoney = BigDecimal.ZERO;
        }
        if(null == AllTradePaymentRechargeCard){
            AllTradePaymentRechargeCard = BigDecimal.ZERO;
        }
        BigDecimal rechargeCardMoney = BigDecimal.ZERO;
        String tradeThirdPartyAmount = "";
        // 退款共用
        GroupBookingTradeDTO groupBookingTrade = this.baseMapper.queryRefundTrade(orderId);
        if(null != groupBookingTrade) {
            // 获取充值卡金额
            rechargeCardMoney = groupBookingTrade.getTradePaymentRechargeCard();
            // 第三方付款金额
            tradeThirdPartyAmount = groupBookingTrade.getTradeThirdPartyAmount().toString();
        }
        double tradeThirdPartyA = 0.00;
        if(org.apache.commons.lang.StringUtils.isNotEmpty(tradeThirdPartyAmount)) {
            tradeThirdPartyA = Double.parseDouble(tradeThirdPartyAmount);
        }
        double tradeThirdPartyB = 0.01;
        BigDecimal weChatTotalFee = allMoney.subtract(AllTradePaymentRechargeCard);
        List<Integer> orderTradeStatus = refundPara.getOrderTradeStatus();
        Set<Integer> set = new HashSet<Integer>(orderTradeStatus);

        if (payCode == 1) {
            // 账户余额
            flag = this.baseMapper.updateUserMoneyResource(userId, money);
        } else if (payCode == 9) {
            // 蜂卡
            flag = this.baseMapper.updateBeeCoinMoney(money, userId);
        } else if (payCode == 10) {
            // 蜂卡+支付宝

        } else if (payCode == 11) {

            // 组合(充值+微信)
        }else if (payCode == 2) {
            // 支付宝
            flag = aliPayRefund(paymentOtherNumber, money);
        } else if (payCode == 3) {
            // 微信
            flag = weChatRefund(paymentOtherNumber, refundOrderId, allMoney, money, orderFrom);
        } else if (payCode == 6) {
            // 充值卡
            flag = this.baseMapper.updateUserRechargeCardMoneyResource(userId, money);
        } else if (payCode == 7) {
            // 组合(充值+支付宝)

        } else if (payCode == 8) {
            // 组合(充值+微信)

        }else if (payCode == 12) {
            //线下付款
            flag = true;

        }

        if (flag) {
            // 更新record退款状态
            this.baseMapper.updateOrderRefund(orderId);
            // 更新trade退款状态
            this.baseMapper.updateOrderTrade(orderId);
            //自营联盟
            this.baseMapper.updateReturnCash(refundPara);
            //分销商
            this.baseMapper.updateDistributorReturn(refundPara);
        }
        return flag;
    }

    @Override
    public Boolean updatebuyTimeOutReturnGoods() {
        List<ReturnOrderDetailVO> orderDetails = this.baseMapper.updatebuyTimeOutReturnGoods();
        if (orderDetails != null && orderDetails.size() > 0){
            Map orderGoodsMap = new HashMap();
            Map updateGoodsMap = new HashMap();
            for (ReturnOrderDetailVO orderDetail : orderDetails) {
                String returnCode = orderDetail.getReturnCode();
                String orderId = orderDetail.getOrderId();
                orderGoodsMap.put("returnCode", returnCode);
                orderGoodsMap.put("returnShopHandle", 13);
                orderGoodsMap.put("returnState", 13);
                orderGoodsMap.put("callStatus", 1);

                orderGoodsMap.put("orderId", orderId);
                Calendar instance = Calendar.getInstance();
                instance.setTime(new Date());
                instance.add(Calendar.DATE,1);
                Date expiration_time = instance.getTime();
                orderGoodsMap.put("expirationTime", expiration_time);
                this.baseMapper.updateOrderBaseById1(orderGoodsMap);

                updateGoodsMap.put("orderId",orderId);
                updateGoodsMap.put("goodsReturnStatus",0);
                updateGoodsMap.put("goodsRefundStatus",0);
                //returnMoneyDao.updateOrderGoodsById2(updateGoodsMap);

                Map<String, Object> updateMap = new HashMap<String, Object>();
                updateMap.put("orderId", orderId);
                updateMap.put("orderRefundStatus","0");
                updateMap.put("orderReturnStatus","0");
                Integer torf = this.baseMapper.updateOrderBaseById(updateMap);
                if (1 != torf) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
                Integer torf1 = this.baseMapper.updateOrderReturnById(orderGoodsMap);
                orderGoodsMap.clear();
                updateGoodsMap.clear();
            }
        }
        return true;
    }

    public void selectYFPayConfig() {

        String paymentMode = "00";//微信 pc  h5
        Map<String, String> outMap = this.baseMapper.selectYfPayConfig(paymentMode);
        WXPayConfig.API_KEY=outMap.get("appAPIKey").toString();
        WXPayConfig.APP_SECRET=outMap.get("appSecret").toString();
        WXPayConfig.MCH_ID=outMap.get("appMCHId").toString();
        WXPayConfig.APP_ID=outMap.get("appID").toString();
        WXPayConfig.NOTIFY_URL=outMap.get("notifyUrl").toString();
        WXPayConfig.REDIRECT_URL=outMap.get("redirectUrl").toString();
        WXPayConfig.weChatWapPath=outMap.get("weChatPcPath").toString();

        //微信app
        WXConfigUtil.KEY=outMap.get("appAPIKey").toString();
        WXConfigUtil.APP_SECRET=outMap.get("appSecret").toString();
        WXConfigUtil.MCH_ID=outMap.get("appMCHId").toString();
        WXConfigUtil.APP_ID=outMap.get("appID").toString();
        WXConfigUtil.NOTIFY_URL_APP= outMap.get("notifyUrl").toString();

        String paymentMode2 = "02";//微信小程序
        Map<String, String> outMap2 = this.baseMapper.selectYfPayConfig(paymentMode2);
        WXPayConfig.Applet_APP_ID=outMap2.get("appID").toString();
        WXPayConfig.Applet_APP_SECRET= outMap2.get("appSecret").toString();


        String paymentMode3 = "03";//支付宝
        outMap = this.baseMapper.selectYfPayConfig(paymentMode3);
        if(null != outMap && !outMap.isEmpty()) {
            ALiPayConfig.URL = outMap.get("gatewayURL").toString();
            ALiPayConfig.APPID = outMap.get("appID").toString();
            ALiPayConfig.sellerId = outMap.get("appMCHId").toString();
            ALiPayConfig.RSA_PRIVATE_KEY = outMap.get("appAPIKey").toString();
            ALiPayConfig.CERT_PATH = outMap.get("cert_public_key_res2").toString();
            ALiPayConfig.ROOT_CERT_PATH = outMap.get("cert_root_key").toString();
            ALiPayConfig.ALIPAY_PUBLIC_CERT_PATH = outMap.get("cert_app_public_key").toString();
            ALiPayConfig.shopping_notify_url = outMap.get("shoppingNotifyUrl").toString();
            ALiPayConfig.shopping_notify_url_h5 = outMap.get("rechargeNotifyUrl2").toString();
            ALiPayConfig.shopping_return_url_pc = outMap.get("shoppingReturnUrlPc").toString();
        }
    }

    public static boolean aliPayRefund(String paymentOtherNumber, BigDecimal money) {
        boolean flag = false;
        try {
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
            // 支付宝网关
            certAlipayRequest.setServerUrl(ALiPayConfig.URL);
            // 应用id
            certAlipayRequest.setAppId(ALiPayConfig.APPID);
            // 应用私钥路径
            certAlipayRequest.setPrivateKey(ALiPayConfig.RSA_PRIVATE_KEY);
            // 应用公钥路径
            certAlipayRequest.setCertPath(ALiPayConfig.ALIPAY_PUBLIC_CERT_PATH);
            // 支付宝应用公钥证书路径
            certAlipayRequest.setAlipayPublicCertPath(ALiPayConfig.CERT_PATH);
            // 支付宝证书，根证书路径
            certAlipayRequest.setRootCertPath(ALiPayConfig.ROOT_CERT_PATH);
            //设置签名
            certAlipayRequest.setSignType(ALiPayConfig.SIGNTYPE);
            // 设置签名类型
            certAlipayRequest.setFormat(ALiPayConfig.FORMAT);
            // 设置编码
            certAlipayRequest.setCharset(ALiPayConfig.CHARSET);
            // 调用RSA签名方式
            AlipayClient client = new DefaultAlipayClient(certAlipayRequest);
            // 设置请求参数
            AlipayTradeRefundModel refundModel = new AlipayTradeRefundModel();
            refundModel.setTradeNo(paymentOtherNumber);
            refundModel.setRefundAmount(money.toString());
            refundModel.setRefundReason("超时退款");
            refundModel.setOutRequestNo("FR" + TimeStampUtil.nowtime() + TimeStampUtil.randomLengthByTwo() + "001");
            // 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            request.setBizModel(refundModel);

            AlipayTradeRefundResponse response = client.certificateExecute(request);
            if (response.isSuccess()) {
                flag = true;
            } else {
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public static boolean weChatRefund(String paymentOtherNumber, String refundOrderId, BigDecimal allMoney,
                                       BigDecimal money, Integer orderFrom) {
        boolean flag = false;
        System.out.println("-----uOrderId-----" + paymentOtherNumber);
        if (orderFrom == 2) {
            // 订单来自wap端
            Map<String, String> params = new HashMap<String, String>();
            params.put("appid", WXPayConfig.APP_ID);
            params.put("mch_id", WXPayConfig.MCH_ID);
            params.put("nonce_str", PayToolUtil.create_nonce_str());
            params.put("transaction_id", paymentOtherNumber);
            params.put("out_refund_no", refundOrderId);
            params.put("total_fee", PayToolUtil.getMoney(allMoney.toString()));
            params.put("refund_fee", PayToolUtil.getMoney(money.toString()));
            String sign = PaymentKit.createSign(params, WXPayConfig.API_KEY);
            params.put("sign", sign);

            System.out.println("abcd = weixin chat wap path = " + WXPayConfig.weChatWapPath);
            File file = new File(WXPayConfig.weChatWapPath);
            String xmlResult = postSSL(WXPayConfig.REFUND_URL,PaymentKit.toXml(params),WXPayConfig.weChatWapPath,WXPayConfig.MCH_ID);
            System.out.println(xmlResult);
            Map<String, String> result = PaymentKit.xmlToMap(xmlResult);

            String return_code = result.get("return_code");
            String return_msg = result.get("return_msg");
            if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
            }
            String result_code = result.get("result_code");
            if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
            } else {
                flag = true;
            }
        } else if (orderFrom == 6) {
            System.out.println("-----进入小程序判断-----");
            Map<String, String> params = new HashMap<String, String>();
            params.put("appid", WXPayConfig.Applet_APP_ID);
            params.put("mch_id", WXPayConfig.MCH_ID);
            params.put("nonce_str", PayToolUtil.create_nonce_str());
            params.put("transaction_id", paymentOtherNumber);
            params.put("out_refund_no", refundOrderId);
            params.put("total_fee", PayToolUtil.getMoney(allMoney.toString()));
            params.put("refund_fee", PayToolUtil.getMoney(money.toString()));
            String sign = PaymentKit.createSign(params, WXPayConfig.API_KEY);
            params.put("sign", sign);

            File file = new File(WXPayConfig.weChatWapPath);

            String xmlResult = postSSL(WXPayConfig.REFUND_URL,PaymentKit.toXml(params),WXPayConfig.weChatWapPath,WXPayConfig.MCH_ID);
            System.out.println(xmlResult);

            Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
            String return_code = result.get("return_code");
            String return_msg = result.get("return_msg");
            if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
            }
            String result_code = result.get("result_code");
            if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
            } else {
                flag = true;
            }
        } else {

            // 其他端
            Map<String, String> params = new HashMap<String, String>();
            params.put("appid", WXPayConfig.APP_ID);
            params.put("mch_id", WXPayConfig.MCH_ID);
            params.put("nonce_str", PayToolUtil.create_nonce_str());
            params.put("transaction_id", paymentOtherNumber);
            params.put("out_refund_no", refundOrderId);
            params.put("total_fee", PayToolUtil.getMoney(allMoney.toString()));
            params.put("refund_fee", PayToolUtil.getMoney(money.toString()));
            String sign = PaymentKit.createSign(params, WXPayConfig.API_KEY);
            params.put("sign", sign);

            File file = new File(WXPayConfig.weChatWapPath);
            if(file.exists()) {
            }
            String xmlResult = "";
            try{
                FileInputStream fileInputStream = new FileInputStream(WXPayConfig.weChatWapPath);
                System.out.println(WXPayConfig.REFUND_URL);
                System.out.println(PaymentKit.toXml(params));
                System.out.println(WXPayConfig.weChatWapPath);
                System.out.println(WXPayConfig.MCH_ID);
                xmlResult = postSSL(WXPayConfig.REFUND_URL,PaymentKit.toXml(params),WXPayConfig.weChatWapPath,WXPayConfig.MCH_ID);
                System.out.println(xmlResult);
            }catch (Exception e){}

            Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
            String return_code = result.get("return_code");
            String return_msg = result.get("return_msg");
            if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
            }
            String result_code = result.get("result_code");
            if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
            } else {
                flag = true;
            }
        }
        return flag;
    }

    public static String postSSL(String url, String data, String certPath, String certPass) {
        String DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36";
        HttpsURLConnection conn = null;
        OutputStream out = null;
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            KeyStore clientStore = KeyStore.getInstance("PKCS12");
            clientStore.load(new FileInputStream(certPath), certPass.toCharArray());
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(clientStore, certPass.toCharArray());
            KeyManager[] kms = kmf.getKeyManagers();
            SSLContext sslContext = SSLContext.getInstance("TLS");

            sslContext.init(kms, null, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            URL _url = new URL(url);
            conn = (HttpsURLConnection) _url.openConnection();

            conn.setConnectTimeout(25000);
            conn.setReadTimeout(25000);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            conn.setRequestProperty("User-Agent", DEFAULT_USER_AGENT);
            conn.connect();
            out = conn.getOutputStream();
            out.write(data.getBytes(Charset.forName("UTF-8")));
            out.flush();
            inputStream = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream,Charset.forName("UTF-8")));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null){
                sb.append(line).append("\n");
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(inputStream);
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    public Boolean updateRefundAccountPeriod(RefundAccountParamDTO param) {
        //退回账期可用额度
        int row = this.baseMapper.updateRefundAccountPeriod(param);
        if (row <= 0) {
            return false;
        }
        //查找账单信息
        AccountShopBillDetailsVO detail = this.baseMapper.selectDetailsByPeriodId(param.getAccountingPeriodId());
        //更改账单状态
        if (detail.getRemainingAccounts().compareTo(BigDecimal.ZERO) == 0) {
            //全部还款
            this.baseMapper.editAccountStatus(param.getAccountingPeriodId(), 2);
        } else if (detail.getRemainingAccounts().compareTo(BigDecimal.ZERO) == 1 && detail.getAccountStatus() != 3) {
            //部分还款且不逾期
            this.baseMapper.editAccountStatus(param.getAccountingPeriodId(), 1);
        }
        //修改账期会员的使用额度跟可用额度
        //查找账期会员的账期信息
        AccountPeriodVO account = this.baseMapper.getAccountPeriodByIds(detail.getShopId(), detail.getUserId());
        BigDecimal amountUsed = account.getAmountUsed().subtract(param.getRefundPrice());
        BigDecimal availableAmount = BigDecimal.ZERO;
        if (account.getAccountIsLimit() != 0) {
            availableAmount = account.getAvailableAmount().add(param.getRefundPrice());
        }
        BigDecimal monthAmountUsed = account.getMonthAmountUsed();
        Boolean isMonth = DateUtil.isMonth(new Date(), detail.getStartTime());
        if (isMonth) {
            monthAmountUsed = account.getMonthAmountUsed().subtract(param.getRefundPrice());
        }
        AccountPeriodParamDTO periodParam = new AccountPeriodParamDTO(detail.getShopId(), detail.getUserId(), amountUsed, availableAmount, monthAmountUsed);
        //更新账期信息
        this.baseMapper.updateAccountPeriod(periodParam);
        return true;
    }

    public void updateGoodsSalenum(Map<String, Object> param) {
        Map<String, Object> esMap = new HashMap<>();
        List<Integer> list = new ArrayList<>();
        try {
            List<Map<String, Object>> goodsNum = (List<Map<String, Object>>) param.get("goodsNum");
            if (null != goodsNum) {
                for (Map<String, Object> map : goodsNum) {
                    //退款 或 退货数量
                    Integer orderGoodsReturnNum = (Integer) map.get("order_goods_returnnum");
                    Integer commonId = (Integer) map.get("common_id");//商品id
                    if (null != commonId && null != orderGoodsReturnNum) {
                        list.add(commonId);
                        //查询当前商品的销量
                        Integer salenum = this.baseMapper.queryCommonNameSalenum(commonId);
                        if (null != salenum) {
                            if (salenum - orderGoodsReturnNum > 0) {
                                this.baseMapper.updateGoodsSalenum(commonId, salenum - orderGoodsReturnNum);
                            } else {
                                this.baseMapper.updateGoodsSalenum(commonId, 0);
                            }
                        }
                    }
                    //更新es
                    map.put("commonIdS", list);
                    // 1 是添加  2是删除
                    map.put("type", 1);
                    MqSendUtils.mqSendGoods(esMap);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void feignUpdateMemberIntegral(MemberMessageListIntegralDTO param) {
        try {
            //获取所有用户id
            List<String> userIdList = param.getUserIdList();
            Integer userIntegral = null;
            Map<String,Object> map = new HashMap<>();
            //type 1是增加积分 0 是扣除积分
            if(param.getType() == 1){
                //便利 添加积分
                for (String userId : userIdList) {
                    //获取当前用户的积分
                    userIntegral = this.baseMapper.queryMemberMessageListIntegral(userId);
                    Integer temp =userIntegral + param.getIntegral();
                    map.put("userid",userId);
                    map.put("integral",temp);
                    this.baseMapper.updateMemberMessageListIntegral(map);
                }
            }else{
                //便利 扣除积分
                for (String userId : userIdList) {
                    //获取当前用户的积分
                    userIntegral = this.baseMapper.queryMemberMessageListIntegral(userId);
                    //如果当前用户的积分 小于 等于 平台扣除的积分直接赋值为 0
                    Integer temp =userIntegral - param.getIntegral();
                    if(temp <= 0){
                        map.put("userid",userId);
                        map.put("integral",0);
                    }else{
                        map.put("userid",userId);
                        map.put("integral",temp);
                    }
                    this.baseMapper.updateMemberMessageListIntegral(map);
                }
            }
            //积分修改完成 修改会员等级
            for (String userId : userIdList) {
                //获取当前用户的积分
                userIntegral = this.baseMapper.queryMemberMessageListIntegral(userId);
                MembershipGradeDTO membershipGrade = this.baseMapper.queryMembershipGradeByGradeRule(userIntegral);
                UpMemberClassDTO upMemberClassDto = new UpMemberClassDTO();
                upMemberClassDto.setMemberClassId(membershipGrade.getId());
                upMemberClassDto.setMemberId(userId);
                this.baseMapper.updateMemeberClass(upMemberClassDto);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ManageShopAddressQueryVO queryReturnShop(Integer returnAddrId,String token) {
        ManageShopAddressQueryVO shopAddress = new ManageShopAddressQueryVO();
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, token);
        if (!userPermissionsResult.getFlag()) {
            return shopAddress;
        }
        shopAddress = this.baseMapper.selectShopAddressDetail(returnAddrId);
        // 设置店铺地址名称
        setShopAddressName(shopAddress);
        return shopAddress;
    }

    /**
     * 设置店铺发货地址的名称
     *
     * @param shopAddress
     */
    private void setShopAddressName(ManageShopAddressQueryVO shopAddress) {
        List<Integer> districtIds = Lists.newArrayList();
        districtIds.add(shopAddress.getShippingAddressProvinceId());
        districtIds.add(shopAddress.getShippingAddressCityId());
        districtIds.add(shopAddress.getShippingAddressAreaId());
        List<String> districtNames = this.baseMapper.selectByIdList(districtIds);
        String shippingAddressArea = "";
        for (String districtName : districtNames) {
            shippingAddressArea = shippingAddressArea + districtName;
        }
        shopAddress.setShippingAddressArea(shippingAddressArea);
    }
    //售后成功  扣除手续费
    public void charging(String orderId,List goodsId,String userId,Integer shopId){
        PlatformoperationVO platformoperation = new PlatformoperationVO();
        //查询平台管理规范
        String configValue = baseServiceClient.selectConfigValueFeign("platform_operation_specifications");
        if (configValue != null ){
            platformoperation = JSONObject.parseObject(configValue, PlatformoperationVO.class);
        }
        //是否开启退费手续费
        Integer configEnable = platformoperation.getConfigEnable();
        //退费通用比例
        BigDecimal universalRatio = BigDecimal.valueOf(platformoperation.getUniversalRatio()).divide(BigDecimal.valueOf(100));
        //扣除手续费总额
        BigDecimal total = BigDecimal.valueOf(0);
        //开启售后手续费
        if (configEnable == 1){
            //查询商品分类
            List<Map> selectgoodscat = this.baseMapper.selectgoodscat(goodsId);
            if (!CollectionUtils.isEmpty(selectgoodscat)){
                for (Map map : selectgoodscat) {
                    Integer id = Integer.valueOf(String.valueOf(map.get("goods_id"))) ;
                    Integer catId = Integer.valueOf(String.valueOf(map.get("cat_id")));
                    //查询商品支付金额
                    //商品实付金额
                    BigDecimal selectgoodsprice = orderGoodsMapper.selectgoodsprice(id, orderId);
                    //退费比例
                    Object refund_proportion = map.get("refund_proportion");
                    if (org.springframework.util.StringUtils.isEmpty(refund_proportion)){
                        //计算退费金额
                        total = total.add(selectgoodsprice.multiply(universalRatio)
                                .setScale(2, BigDecimal.ROUND_HALF_UP));

                    }else{
                        BigDecimal refundProportion = BigDecimal.valueOf(Long.parseLong(String.valueOf(map.get("refund_proportion")))).divide(BigDecimal.valueOf(100));
                        //计算退费金额
                        total = total.add(selectgoodsprice.multiply(refundProportion)
                                .setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                }
                //获取商家质保金余额
                Integer selectshop = this.baseMapper.selectshop(shopId);
                BigDecimal bigDecimal = new BigDecimal(selectshop);
                if (bigDecimal.compareTo(new BigDecimal(0)) <= 0 || bigDecimal.compareTo(total) < 0) {
                    //质保金余额不足 暂不赔付
                    insertcom(total,orderId,0,shopId,goodsId);
                } else {
                    //罚扣质保金
                    insertcom(total,orderId,1,shopId,goodsId);
                }
                updateshopmoney(shopId,total,userId);

            }
        }
    }
    //插入罚扣质保金记录
    @Transactional
    public void insertcom(BigDecimal multiply,String orderId,Integer status,Integer shopId,List goodsId){
        HashMap<String, Object> map = new HashMap<>();
        //生成投诉单号
        StringBuffer id = new StringBuffer("TS");
        DateFormat dFormat3 = new SimpleDateFormat("yyyyMMdd");

        String format = dFormat3.format(new Date());

        Random random = new Random();
        String verificationCode = String.valueOf(random.nextInt(9) + 1);
        for (int i = 0; i < 5; i++) {
            verificationCode += random.nextInt(10);
        }
        id.append(format).append(verificationCode);
        map.put("complaintsId", id.toString());
        //买家id
        map.put("userId",null);
        map.put("complaintsStatus", 1);
        //退费金额
        map.put("compensationAmount", multiply);
        //是否赔付
        map.put("compensationStatus", status);
        map.put("orderId",orderId);
        map.put("complaintsType",5);
        map.put("fundDestination",2);
        map.put("shopId",shopId);
        String s = JSON.toJSONString(goodsId);
        map.put("complaintsGoodsid",s);
        map.put("createTime", DateUtils.getNowDate());
        //插入质保金罚扣记录
        orderComplaintsMapper.addcomplaints(map);
    }
    //罚扣质保金
    @Transactional
    public Integer updateshopmoney(Integer shopId,BigDecimal amount,String userId){
        RetentionShopInfoVO selectretention = orderComplaintsMapper.selectretention(shopId);
        //质保金余额-
        BigDecimal payPrice = selectretention.getRetentionMoneyBalance().subtract(amount);

        //质保金可提现
        BigDecimal payPrice1 = payPrice.subtract(selectretention.getRetentionMoneyLimit());
        if (payPrice1.compareTo(new BigDecimal(0)) == -1) {
            payPrice1 = new BigDecimal(0);
        }

        //待补缴
        BigDecimal payPrice2 = new BigDecimal(0);
        if (payPrice.compareTo(selectretention.getRetentionMoneyLimit()) < 0) {
            //待补缴金额
            payPrice2 = selectretention.getRetentionMoneyLimit().subtract(payPrice);
            if (payPrice2.compareTo(new BigDecimal(0)) == -1) {
                payPrice2 = new BigDecimal(0);
            }
        }

        //累计赔付金额
        BigDecimal payPrice3 = selectretention.getAccumulatedCompensation().add(amount);
        HashMap<Object, Object> paymap = new HashMap<>();
        paymap.put("payPrice", payPrice);
        paymap.put("payPrice1", payPrice1);
        paymap.put("payPrice2", payPrice2);
        paymap.put("payPrice3", payPrice3);
        paymap.put("shopId", shopId);
        if (payPrice.compareTo(selectretention.getRetentionMoneyLimit()) >= 0) {
            paymap.put("retentionStatus", 1);
        } else if (payPrice.compareTo(new BigDecimal(0)) >= 0 && payPrice2.compareTo(new BigDecimal(0)) > 0) {
            //发送站内信
            String content = "亲爱的卖家您好，根据平台质保金规则您需补缴" + payPrice2 + " 元质保金，请登录商家后台查询。";
            orderComplaintsMapper.insertSysMessage1("",userId,"",5,
                    "补缴质保金",content, String.valueOf(shopId));
            paymap.put("retentionStatus", 2);
        } else if (payPrice.compareTo(new BigDecimal(0)) == -1) {
            //发送站内信
            String content = "亲爱的卖家您好，根据平台质保金规则您需补缴" + payPrice2 + " 元质保金，请登录商家后台查询。";
            orderComplaintsMapper.insertSysMessage1("",userId,"",5,
                    "补缴质保金",content, String.valueOf(shopId));
            paymap.put("paymentTime", new Date());//质保金状态
            paymap.put("retentionStatus", 3);
        }
        //更新shopbase表
        if(selectretention.getRetentionStatus() == 3){
            paymap.put("paymentTime", null);
        }
        return orderComplaintsMapper.updateshopbase(paymap);
    }
    //退还优惠卷红包
    public void returnred(String orderId,BigDecimal returnCash,List<Integer> returnGoods){
        try {
            Map map1 = orderBaseMapper.queryorderpaymentamount(orderId);
            //订单实付金额
            BigDecimal orderpay = new BigDecimal(String.valueOf(map1.get("order_payment_amount")));
            //订单邮费
            BigDecimal orderShippingFee = new BigDecimal(String.valueOf(map1.get("order_shipping_fee")));
            //查询红包和代金卷
            WapGoodsSaleSumUpdateVO wap = orderBaseMapper.queryRedByEnvelope(orderId);

            BigDecimal payGoods = orderGoodsMapper.selectPayGoods(orderId,returnGoods);
            BigDecimal feeGoods = orderGoodsMapper.selectFeeGoods(orderId,returnGoods);
            if(returnCash.compareTo(payGoods.subtract(feeGoods)) >= 0){
                for (Integer returnGood : returnGoods) {
                    Integer voucherId = orderGoodsMapper.selectOne(new LambdaQueryWrapper<OrderGoodsEntity>()
                            .eq(OrderGoodsEntity::getOrderId,orderId)
                            .eq(OrderGoodsEntity::getGoodsId,returnGood)).getVoucherId();
                    if(voucherId != null && !voucherId.toString().equals("0")) {
                        this.baseMapper.updateCouponStuate(voucherId.toString());
                    }
                }
            }

            if (null != wap) {
                //订单总金额 - 运费
                if (returnCash.compareTo(orderpay.subtract(orderShippingFee)) >= 0) {
                    if (!org.springframework.util.StringUtils.isEmpty(wap.getVoucherCode())) {
                        String[] voucherNoList = wap.getVoucherCode().split("-");
                        for (String voucherId : voucherNoList) {
                            //退还代金卷
                            this.baseMapper.updateCouponStuate(voucherId);
                        }
                    }
                }
                if (orderpay.compareTo(returnCash) == 0) {
                    //全退返还红包
                    if (!org.springframework.util.StringUtils.isEmpty(wap.getRedpacketCode())) {
                        //根据订单号查询支付单号 因为有可能多个订单公用一个支付单号 如果是多个订单共用用一个支付单号 要判断除当前退单外的其他订单是否是全退
                        String paymentNumber = this.baseMapper.queryOrderPaymentNumber(orderId);
                        //如果多个订单公用一个支付单号 根据当前订单号 和 支付单号 查询是否有其他订单没有全退货
                        List orderIds = this.baseMapper.queryOrderId(orderId, paymentNumber);
                        if (CollectionUtils.isEmpty(orderIds)) {
                            //无其他订单 退还红包
                            this.baseMapper.updateRedPageStuate(wap.getRedpacketCode());
                        } else {
                            //查询其他订单是否全额退款
                            List<Map> maps = this.baseMapper.queryOrderreturn(orderIds);
                            boolean s = true;
                            if (!CollectionUtils.isEmpty(maps)) {
                                for (Map map2 : maps) {
                                    //判断其他订单是否全额退款
                                    //实付金额
                                    BigDecimal paymentAmount = new BigDecimal(String.valueOf(map2.get("order_payment_amount")));
                                    //退款金额
                                    BigDecimal returnCash1 = new BigDecimal(String.valueOf(map2.get("return_cash")));
                                    if (paymentAmount.compareTo(returnCash1) > 0) {
                                        s = false;
                                        break;
                                    }
                                }

                                if (s) {
                                    //退还红包
                                    this.baseMapper.updateRedPageStuate(wap.getRedpacketCode());
                                }
                            }
                        }

                    }
                }
            }
        }catch (Exception e){
            System.err.println(e.getMessage());
        }
    }
    //计算用户退还积分
    public void refundpoints(String orderId,BigDecimal returnCash){
        //根据orderid 查询应该回退的积分和userid
        Map<String, Object> map = this.baseMapper.queryAddpointsLogByOrderId(orderId);

        //ZZZ 新增积分按比例扣除逻辑
        //订单实付金额
        BigDecimal order_payment_amount = this.baseMapper.queryOrderAmount(orderId);
        //订单退款金额
        BigDecimal returnAmount = returnCash;

        BigDecimal tmp = BigDecimal.ZERO;
        if (null != map && null != map.get("points_log_points")) {
            tmp = returnAmount.multiply(new BigDecimal((Integer) map.get("points_log_points")).divide(order_payment_amount, RoundingMode.HALF_UP));
        }
        Integer tmpInt = tmp.intValue();
        map.put("points_log_points", tmpInt);

        //修改会员积分和会员等级
        MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
        ArrayList<String> list = new ArrayList<>();
        list.add((String) map.get("user_id"));
        updateMemberMessageListIntegral.setUserIdList(list);
        updateMemberMessageListIntegral.setIntegral((Integer) map.get("points_log_points"));
        //1是增加积分 0 是扣除积分
        updateMemberMessageListIntegral.setType(0);
        feignUpdateMemberIntegral(updateMemberMessageListIntegral);
        //添加积分修改记录
        UserPointLogParamDTO userPointLog = new UserPointLogParamDTO();
        userPointLog.setPointsLogType(2);
        userPointLog.setClassId(9);
        userPointLog.setPointsLogTime(new Date());
        userPointLog.setPointsLogDesc("商品仅退款");
        userPointLog.setPointsLogFlag("reg");
        userPointLog.setUserId(map.get("user_id").toString());
        userPointLog.setPointsLogPoints((Integer) map.get("points_log_points"));
        userPointLog.setPointsLogOperate("商品仅退款");
        userPointLog.setOrderId(orderId);
        this.baseMapper.feginAddpointsLog(userPointLog);
    }
}




